Data Analysis & SQL5.0 · 0 ratings

Build A Slowly Changing Dimension Type 2

Implements SCD Type 2 history tracking with effective dates, current flags, and a correct merge in SQL.

Role-BasedStep-by-StepStructured-Output

Prompt

ROLE: You are a data warehouse engineer implementing slowly changing dimensions.

CONTEXT: Maintain history for dimension [DIM_NAME] sourced from [SOURCE_TABLE]. The natural key is [NATURAL_KEY]; the tracked attributes whose changes must create new versions are [TRACKED_ATTRS]. Engine: [DATABASE_ENGINE].

TASK:
1. Define the SCD2 columns: surrogate key, natural key, tracked attributes, valid_from, valid_to, is_current, and a row hash of tracked attributes for change detection.
2. Explain the change-detection logic: a new version is created only when a tracked attribute changes (compare hashes), not on every load.
3. Write the upsert/merge logic that (a) closes the current row (set valid_to, is_current = false) and (b) inserts the new version when a change is detected, while leaving unchanged records alone.
4. Show how to query the dimension as-of a given date.
5. Handle first-load, late-arriving changes, and deletes (soft expire).

OUTPUT FORMAT: Column design -> Change-detection rule -> Merge/upsert ```sql``` -> As-of point-in-time query -> Edge cases (first load, late data, deletes).

CONSTRAINTS: valid_from/valid_to must be contiguous and non-overlapping per natural key, with exactly one is_current = true. Use half-open intervals. Compare hashes to avoid spurious versions. State the timezone/granularity of effective dates.

How to use this prompt

  1. 1

    Copy the prompt above and paste it into ChatGPT, Claude, or Gemini — or open it in the visual Studio to edit each part on a canvas and run it with your own key.

  2. 2

    Replace any bracketed placeholders with your specifics. The more concrete your context and constraints, the sharper the result — see the 5-part prompt structure.

  3. 3

    Run it, then refine. Ask the model to critique and improve its own answer with self-critique prompting.

Techniques in this prompt

Role-Based

Assigns the model an expert persona so it adopts the right vocabulary, depth, and standards for the task.

Learn this technique
Step-by-Step

Forces explicit intermediate reasoning instead of jumping to a conclusion, which improves accuracy on hard tasks.

Learn this technique
Structured Output

Pins the response to a defined structure so it drops straight into your workflow.

Learn this technique

Recommended models

claudegpt-4ogemini

Build on this prompt

Open it in the visual Studio to wire it into a full workflow with your own API key — or learn the craft behind prompts like this.

More in Data Analysis & SQL