How To Pivot Table In Sql

5 min read

Pivoting data in SQL transforms rows into columns, turning long, narrow datasets into wide, analytical summaries that are far easier for humans to read and for reporting tools to visualize. Even so, whether you are building a sales dashboard, analyzing survey responses, or preparing data for a spreadsheet, mastering the pivot operation is a fundamental skill for any data analyst or engineer. On top of that, while the concept remains consistent across databases, the syntax varies significantly between platforms like SQL Server, PostgreSQL, MySQL, Oracle, and Snowflake. This guide provides a comprehensive walkthrough of the logic, standard syntax, and platform-specific implementations required to pivot tables effectively in SQL Simple, but easy to overlook..

Real talk — this step gets skipped all the time.

Understanding the Core Concept: Rows to Columns

Before diving into syntax, it is crucial to visualize the structural change a pivot performs. Also, imagine a table recording monthly sales for different products. Even so, in a normalized (long) format, you have three columns: Product, Month, and Sales_Amount. Each row represents a single data point Still holds up..

Product Month Sales_Amount
Laptop Jan 1000
Laptop Feb 1200
Mouse Jan 50
Mouse Feb 60

A pivot operation rotates this structure. The unique values in the Month column (Jan, Feb) become new column headers. The Sales_Amount values fill the intersecting cells, grouped by the remaining identifier column (Product).

Product Jan Feb
Laptop 1000 1200
Mouse 50 60

Three elements define every pivot operation:

  1. The Grouping Column (Row Identifier): The column(s) that remain as rows (Product). Also, 2. This leads to The Spreading Column (Pivot Column): The column whose distinct values become new column headers (Month). Think about it: 3. The Aggregation Column (Value Column): The column containing the data to be summarized, requiring an aggregate function like SUM, AVG, COUNT, MAX, or MIN (Sales_Amount).

The Standard Approach: Conditional Aggregation (ANSI SQL)

The most portable, performant, and universally supported method for pivoting in SQL uses Conditional Aggregation with CASE expressions inside aggregate functions. This technique works identically in PostgreSQL, MySQL, SQLite, Oracle, SQL Server, and BigQuery without requiring proprietary extensions The details matter here..

Syntax Pattern

SELECT
    grouping_column,
    SUM(CASE WHEN spreading_column = 'value1' THEN aggregation_column ELSE 0 END) AS value1,
    SUM(CASE WHEN spreading_column = 'value2' THEN aggregation_column ELSE 0 END) AS value2,
    -- Repeat for all distinct values
FROM source_table
GROUP BY grouping_column;

Practical Example

Using the sales scenario above, here is the ANSI SQL query:

SELECT
    Product,
    SUM(CASE WHEN Month = 'Jan' THEN Sales_Amount ELSE 0 END) AS Jan_Sales,
    SUM(CASE WHEN Month = 'Feb' THEN Sales_Amount ELSE 0 END) AS Feb_Sales,
    SUM(CASE WHEN Month = 'Mar' THEN Sales_Amount ELSE 0 END) AS Mar_Sales
FROM Monthly_Sales
GROUP BY Product;

Why this is often the best choice:

  • Portability: Runs on virtually any RDBMS.
  • Control: You explicitly define column names and ordering.
  • Performance: The optimizer treats this as a standard GROUP BY with filtered aggregates, often utilizing indexes efficiently.
  • Handling NULLs: The ELSE 0 (or ELSE NULL) clause gives you precise control over how missing data appears.

Proprietary PIVOT Operators: Platform Specifics

Major vendors have introduced native PIVOT keywords to simplify syntax. While convenient, these lock your code into a specific dialect.

SQL Server (T-SQL) & Azure Synapse

SQL Server introduced the PIVOT operator in 2005. It requires you to know the spreading values upfront (static pivot) And it works..

SELECT Product, [Jan], [Feb], [Mar]
FROM
(
    SELECT Product, Month, Sales_Amount
    FROM Monthly_Sales
) AS SourceTable
PIVOT
(
    SUM(Sales_Amount)
    FOR Month IN ([Jan], [Feb], [Mar])
) AS PivotTable;

Key Notes:

  • Square brackets [] are required for column aliases if they are reserved words or contain spaces.
  • The subquery (SourceTable) defines the three input columns: Grouping, Spreading, Aggregation.
  • UNPIVOT exists for the reverse operation.

Oracle Database

Oracle’s syntax is similar but uses the PIVOT clause directly in the FROM clause and supports XML output for dynamic columns Most people skip this — try not to..

SELECT * FROM
(
    SELECT Product, Month, Sales_Amount
    FROM Monthly_Sales
)
PIVOT
(
    SUM(Sales_Amount)
    FOR Month IN ('Jan' AS Jan_Sales, 'Feb' AS Feb_Sales, 'Mar' AS Mar_Sales)
);

Oracle Advantage: You can alias the output columns directly inside the IN clause ('Jan' AS Jan_Sales), resulting in cleaner final column names without wrapping the whole query Most people skip this — try not to..

Snowflake & BigQuery (Modern Cloud Warehouses)

Snowflake supports a syntax very similar to SQL Server but allows the PIVOT clause to follow the table name directly Not complicated — just consistent..

SELECT *
FROM Monthly_Sales
PIVOT(SUM(Sales_Amount) FOR Month IN ('Jan', 'Feb', 'Mar'))
AS p (Product, Jan_Sales, Feb_Sales, Mar_Sales);

BigQuery uses a slightly different structure, often requiring the PIVOT operator inside the FROM clause:

SELECT * FROM
(
    SELECT Product, Month, Sales_Amount FROM Monthly_Sales
)
PIVOT(SUM(Sales_Amount) FOR Month IN ('Jan', 'Feb', 'Mar'));

PostgreSQL: The crosstab Function

PostgreSQL does not have a native PIVOT keyword in standard SQL. Instead, it relies on the tablefunc extension and the crosstab function. This is powerful but requires setup.

1. Enable Extension (Run once per database):

CREATE EXTENSION IF NOT EXISTS tablefunc;

2. Execute Crosstab: crosstab returns a SETOF record, meaning you must define the output column structure in the calling query That alone is useful..

SELECT *
FROM crosstab(
    'SELECT Product, Month, Sales_Amount FROM Monthly_Sales ORDER BY 1,2',
    'SELECT DISTINCT Month FROM Monthly_Sales ORDER BY 1'
) AS ct(Product TEXT, Jan NUMERIC, Feb NUMERIC, Mar NUMERIC);
  • Argument 1 (Source SQL): Must return 3 columns: Row Header, Category, Value. Must be ordered by Row Header, then Category.
  • Argument 2 (Category SQL): Returns the distinct categories in the desired output order.
  • Alias Definition (AS ct(...)): Mandatory. Defines the name and data type of every output column.

MySQL: Conditional Aggregation Only

MySQL (up to version 8.In practice, 0+) does not support a native PIVOT keyword. On top of that, you must use the Conditional Aggregation method described in the ANSI section. This is not a limitation; the optimizer handles CASE statements inside aggregates extremely well.

Handling Dynamic Pivots: When Columns Are Unknown

In real-world scenarios, you often do not know the distinct values of the spreading column (e.g., "All months present in the data") beforehand

New on the Blog

Out the Door

See Where It Goes

Continue Reading

Thank you for reading about How To Pivot Table In Sql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home