Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to rotate rows to columns and columns to rows in SQL. Compare native PIVOT and UNPIVOT in SQL Server with cross-platform CASE expressions.
Quick answer
SQL PIVOT rotates row-level category values into distinct output columns for aggregation, while UNPIVOT transforms column headers back into normalized row values. You can execute pivots using vendor-specific PIVOT syntax in SQL Server and BigQuery, or cross-platform conditional aggregation with CASE expressions.
FAQs
Can I pivot columns dynamically in standard SQL without knowing column names upfront?
Standard SQL requires column names to be declared explicitly in the query. Dynamic pivoting requires generating and executing dynamic SQL strings via stored procedures.
Is conditional aggregation slower than native PIVOT in SQL Server?
In most cases, SQL Server compiles both conditional aggregation and native PIVOT into virtually identical execution plans.
How do I handle NULL values when pivoting columns?
Wrap your aggregation in COALESCE or specify ELSE 0 in the conditional CASE statement to replace NULL values with zeros.
Does PostgreSQL have a native PIVOT command?
PostgreSQL does not have a native PIVOT keyword. You achieve pivoting using conditional aggregation or the crosstab() function from the tablefunc extension.
Master SQL LATERAL joins across PostgreSQL and MySQL 8. Learn how to write correlated subqueries in FROM clauses and solve the classic top-N per group problem.
Relational databases store data in normalized rows, but business stakeholders and reporting tools often require wide tables with categories displayed horizontally as columns. Transforming row-based data into columns is called pivoting. Rotating columns back into rows is unpivoting.
While proprietary SQL dialects like SQL Server and BigQuery provide native PIVOT and UNPIVOT keywords, standard ANSI SQL solves pivoting through conditional aggregation with CASE expressions. Understanding both methods enables you to write clean, portable data transformations across any database engine.
Rows vs columns: the fundamental shape problem
In transaction processing systems, transactional sales data is recorded as one row per sale with category attributes. A sales table might store millions of rows where each row contains a year, quarter, and revenue.
In financial reporting, users want a single row per year with four distinct columns: Q1_Revenue, Q2_Revenue, Q3_Revenue, and Q4_Revenue. Rotating rows to columns groups the records by identity while transposing category values into horizontal metrics.
Cross-platform pivoting with conditional aggregation
The most dependable way to pivot data across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery is conditional aggregation. You group by your row identifier and wrap individual CASE statements inside an aggregate function like SUM() or MAX(). Check our guide to SQL CASE statement formatting for styling recommendations.
Conditional aggregation pivot syntax
-- Normalized sales table structure-- Columns: sales_year, quarter_name, revenueSELECT sales_year, SUM(CASE WHEN quarter_name = 'Q1' THEN revenue ELSE 0 END) AS q1_revenue, SUM(CASE WHEN quarter_name = 'Q2' THEN revenue ELSE 0 END) AS q2_revenue, SUM(CASE WHEN quarter_name = 'Q3' THEN revenue ELSE 0 END) AS q3_revenue, SUM(CASE WHEN quarter_name = 'Q4' THEN revenue ELSE 0 END) AS q4_revenue, SUM(revenue) AS total_annual_revenueFROM company_quarterly_salesGROUP BY sales_yearORDER BY sales_year DESC;
This query is portable across every SQL engine. It runs efficiently, handles missing values gracefully with ELSE 0, and allows you to format each column clearly in code reviews.
Native T-SQL PIVOT syntax in SQL Server
SQL Server provides a dedicated PIVOT operator in the FROM clause. The syntax requires specifying the aggregation function, the pivot column, and the list of pivoted column headers in brackets.
SQL Server PIVOT query
SELECT sales_year, [Q1] AS q1_revenue, [Q2] AS q2_revenue, [Q3] AS q3_revenue, [Q4] AS q4_revenueFROM ( -- Source query must select ONLY columns needed for grouping, pivoting, and aggregation SELECT sales_year, quarter_name, revenue FROM company_quarterly_sales) AS SourceTablePIVOT ( SUM(revenue) FOR quarter_name IN ([Q1], [Q2], [Q3], [Q4])) AS PivotTableORDER BY sales_year DESC;
According to Microsoft Learn documentation on PIVOT and UNPIVOT, any column in the source table not listed in the aggregate or pivot clause is automatically included as an implicit GROUP BY column. For this reason, always feed the PIVOT operator from an explicit subquery or CTE.
UNPIVOT: converting columns back into rows
The reverse problem occurs when you import spreadsheet data formatted with wide columns and need to normalize it for database storage. UNPIVOT converts column headers into row values.
SQL Server UNPIVOT query
-- Wide table: employee_scores-- Columns: employee_id, comms_score, tech_score, leadership_scoreSELECT employee_id, skill_category, rating_scoreFROM ( SELECT employee_id, comms_score, tech_score, leadership_score FROM employee_assessments) AS WideSourceUNPIVOT ( rating_score FOR skill_category IN ( comms_score, tech_score, leadership_score )) AS UnpivotTable;
In PostgreSQL and SQLite, which lack a native UNPIVOT keyword, you can unpivot using CROSS JOIN LATERAL with VALUES clauses or multiple UNION ALL statements. In BigQuery, native UNPIVOT works similarly to T-SQL per the Google Cloud BigQuery query reference.
Formatting and readability conventions for pivot queries
Pivot queries easily become unreadable when columns are cramped onto a single line. Follow these formatting guidelines:
Place each pivoted column definition on its own indented line.
Align the AS alias cleanly to make column names obvious in diffs.
Isolate the source dataset in a Common Table Expression (CTE) before feeding it to PIVOT.
Provide explicit zero fallbacks with COALESCE or ELSE 0 to avoid NULL values in matrix reports.
Actionable checklist for writing pivot queries
Isolate columns: use an explicit CTE or derived table to prevent unintended grouping columns.
Choose method: use conditional aggregation (CASE) for portability, or native PIVOT for conciseness in T-SQL or BigQuery.
Handle nulls: verify whether unpopulated cells should display NULL or 0 in output reports.
Check data types: ensure all columns participating in UNPIVOT share identical data types and precision.
Format column lists: place each pivoted column header on its own line for clean Git diffs.
Profile execution: verify that the database creates an efficient aggregation plan without spooling to disk.
Wrapping up
Rotating data between wide and narrow formats is a core skill for SQL developers and analysts. While native PIVOT operators offer concise syntax in SQL Server and BigQuery, conditional aggregation with CASE expressions provides universal portability across all database engines. Keep your complex pivot queries cleanly structured by formatting your SQL with sqlfmt or checking out our Pro subscription for automated team formatting.