Pivot / Unpivot

SQL · Extra Concepts

Theory

PIVOT turns values that sit in rows into separate columns. A sales table with one row per (city, quarter) becomes a report with one row per city and columns Q1, Q2, Q3. UNPIVOT does the reverse: it turns those quarter columns back into rows, which is often needed before loading a spreadsheet-style file into a proper table.

SQL Server, Oracle and Snowflake have a native PIVOT clause, but the column list must usually be written out in advance. The portable method that works everywhere, including SQLite, MySQL and PostgreSQL, is conditional aggregation: GROUP BY the row label and write one SUM(CASE WHEN quarter = 'Q1' THEN amount END) AS Q1 per output column. CASE returns NULL for non-matching rows, and SUM ignores NULLs, so each column only adds its own quarter. Combinations with no data come out as NULL; wrap them in COALESCE(..., 0) if you want zeros. UNPIVOT can be emulated with UNION ALL of one SELECT per column.

Why we use it

Reports and dashboards are usually wide (one column per month or category), while databases store data long (one row per fact). PIVOT reshapes long data into the readable cross-tab people expect.

When to use it

Use PIVOT or CASE-based pivots for final report layouts with a known, small set of columns. Keep data long for storage and further analysis. For a changing set of categories, pivot in the BI tool or build the SQL dynamically.

How it works

  1. Start with long data: one row per city and quarter
  2. Choose the row label (city) and the column source (quarter)
  3. GROUP BY the row label
  4. For each output column: SUM(CASE WHEN quarter = 'Q1' THEN amount END)
  5. Any city-quarter with no data? Yes: NULL — COALESCE(..., 0). No: Keep the totals.
  6. Wide report: one row per city

Syntax

SELECT * FROM table
PIVOT (AGG(value) FOR column IN (val1, val2))

Example

SELECT
  SUM(CASE WHEN department='IT' THEN salary END) AS IT,
  SUM(CASE WHEN department='HR' THEN salary END) AS HR
FROM employees;

Key points

SQL topics

Introduction to SQL

Querying Data

Sorting Rows

Limiting Rows

Filtering Rows

Joining Multiple Tables

Grouping Rows

SET Operators

Working with Tables

Modifying Data

Views & Triggers

Conditional Expressions

SQL Subqueries

Aggregate Functions

Window Functions

String Functions

Date Functions

Math Functions

Extra Concepts

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master SQL from Zero to Pro

All SQL topics in one place. Click any topic in the sidebar — content opens right here without leaving the page.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice SQL Online Solve 150 SQL interview problems in a live editor with instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

SQL  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs against a real sample database
{{ liveError }}
{{ col }}
{{ cell }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic