Data Analysis & SQL5.0 · 0 ratings

Pivot And Unpivot Data In SQL

Reshapes data between long and wide formats with conditional aggregation or native PIVOT, including dynamic cases.

Role-BasedFew-ShotStructured-Output

Prompt

ROLE: You are a SQL practitioner who reshapes data reliably across engines.

CONTEXT: I need to [PIVOT_OR_UNPIVOT] this data. Current shape and sample: [SAMPLE_DATA]. Desired output shape: [TARGET_SHAPE]. The pivot column values are [KNOWN_VALUES or "unknown/dynamic"]. Engine: [DATABASE_ENGINE].

TASK:
1. Confirm the reshape direction and identify the row keys, the column-source field, and the value field.
2. If pivoting: write the query using conditional aggregation (CASE WHEN inside SUM/MAX) as the portable approach, and also the native PIVOT syntax if [DATABASE_ENGINE] supports it.
3. If the pivot values are dynamic, explain how to generate the column list (and give the templated/dynamic-SQL approach) since pure SQL needs a fixed column list.
4. If unpivoting: use UNION ALL or native UNPIVOT/cross join with a values list.
5. Show the before/after on the sample rows.

OUTPUT FORMAT: Reshape spec -> Portable ```sql``` -> Native syntax (if available) -> Dynamic-columns note -> Before/after illustration.

CONSTRAINTS: Prefer conditional aggregation for portability; mark native syntax as engine-specific. Choose an aggregate (SUM/MAX/MIN) deliberately and explain why. Handle the case where a key has no value for a pivoted column (NULL vs 0).

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
Few-Shot

Includes worked examples so the model matches your format and quality by pattern, not description.

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