To pivot data in SQL, group by the column you want as rows and use one SUM(CASE WHEN ... THEN ... END) per value you want as a column. This works in every database. SQL Server also has a PIVOT operator, PostgreSQL has crosstab(), and you reverse a pivot (unpivot) with UNION ALL or SQL Server’s UNPIVOT.

Databases store data long: one row per fact, like one row per category and status. People read data wide: one row per category, with a column for each status, like a spreadsheet pivot table. Pivoting is how you get from one shape to the other, and it’s one of the most requested report formats.

This lesson of the Learn SQL series builds on CASE expressions and aggregate functions. The examples use the series’ sample database: download shop.sql and load it as shown in Part 1. Everything was tested on PostgreSQL, MySQL 8, SQL Server, and SQLite.

Long Data vs. Wide Data

Here’s revenue by category and order status, the way a GROUP BY returns it:

SELECT p.category,
       o.status,
       SUM(o.quantity * p.price) AS revenue
FROM orders o
JOIN products p ON p.product_id = o.product_id
GROUP BY p.category, o.status
ORDER BY p.category, o.status;
  category   |  status   | revenue
-------------+-----------+---------
 Accessories | pending   |  125.00
 Accessories | shipped   |  165.00
 Electronics | returned  |  899.00
 Electronics | shipped   | 3444.00
 Furniture   | cancelled |  360.00
 Furniture   | pending   |  320.00
 Furniture   | shipped   | 1040.00

That’s long data. It’s correct, but hard to compare at a glance. The wide version puts one category per row and one status per column. Let’s build it.

Pivoting with CASE and GROUP BY (Works Everywhere)

The portable way to pivot is conditional aggregation:

  1. GROUP BY the column that becomes the rows (category).
  2. For each new column, add up only the rows that belong in it, using CASE.
SELECT p.category,
       SUM(CASE WHEN o.status = 'shipped'   THEN o.quantity * p.price ELSE 0 END) AS shipped,
       SUM(CASE WHEN o.status = 'pending'   THEN o.quantity * p.price ELSE 0 END) AS pending,
       SUM(CASE WHEN o.status = 'returned'  THEN o.quantity * p.price ELSE 0 END) AS returned,
       SUM(CASE WHEN o.status = 'cancelled' THEN o.quantity * p.price ELSE 0 END) AS cancelled
FROM orders o
JOIN products p ON p.product_id = o.product_id
GROUP BY p.category
ORDER BY p.category;
  category   | shipped | pending | returned | cancelled
-------------+---------+---------+----------+-----------
 Accessories |  165.00 |  125.00 |        0 |         0
 Electronics | 3444.00 |       0 |   899.00 |         0
 Furniture   | 1040.00 |  320.00 |        0 |    360.00

Each CASE looks at one row at a time: if the status matches, it returns the order’s revenue; otherwise it returns 0. SUM then adds up each column separately within each category. (PostgreSQL shows the zeros as 0 instead of 0.00; the value is the same.)

Pivoting by Month

The same pattern turns dates into columns. Shipped revenue per category, by month, plus a total:

SELECT p.category,
       SUM(CASE WHEN o.order_date >= '2025-08-01' AND o.order_date < '2025-09-01'
                THEN o.quantity * p.price ELSE 0 END) AS aug,
       SUM(CASE WHEN o.order_date >= '2025-09-01' AND o.order_date < '2025-10-01'
                THEN o.quantity * p.price ELSE 0 END) AS sep,
       SUM(CASE WHEN o.order_date >= '2025-10-01' AND o.order_date < '2025-11-01'
                THEN o.quantity * p.price ELSE 0 END) AS oct,
       SUM(CASE WHEN o.order_date >= '2025-11-01' AND o.order_date < '2025-12-01'
                THEN o.quantity * p.price ELSE 0 END) AS nov,
       SUM(o.quantity * p.price) AS total
FROM orders o
JOIN products p ON p.product_id = o.product_id
WHERE o.status = 'shipped'
GROUP BY p.category
ORDER BY total DESC;
  category   |  aug   |  sep   |   oct   | nov |  total
-------------+--------+--------+---------+-----+---------
 Electronics | 899.00 | 498.00 | 2047.00 |   0 | 3444.00
 Furniture   | 320.00 | 720.00 |       0 |   0 | 1040.00
 Accessories | 165.00 |      0 |       0 |   0 |  165.00

Date ranges (>= the first day and < the first day of the next month) work the same in every database and can use an index on order_date, as explained in the date and time functions lesson. The total column is a plain SUM, since it includes every month.

Counting Instead of Adding

To count rows instead of adding amounts, return 1 for a match. Orders by state, split by status:

SELECT c.state,
       COUNT(*) AS orders,
       SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
       COUNT(CASE WHEN o.status <> 'shipped' THEN 1 END)     AS not_shipped
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
GROUP BY c.state
ORDER BY c.state;
 state | orders | shipped | not_shipped
-------+--------+---------+-------------
 AZ    |      3 |       2 |           1
 CA    |      8 |       5 |           3
 NV    |      1 |       1 |           0

Both styles work: SUM(CASE ... THEN 1 ELSE 0 END) adds ones and zeros, and COUNT(CASE ... THEN 1 END) counts the non-NULL values, because a CASE without ELSE returns NULL when nothing matches.

ELSE 0 or No ELSE?

That NULL matters when you add amounts:

SELECT p.category,
       SUM(CASE WHEN o.status = 'returned' THEN o.quantity * p.price END) AS returned_no_else,
       SUM(CASE WHEN o.status = 'returned' THEN o.quantity * p.price ELSE 0 END) AS returned_else_0
FROM orders o
JOIN products p ON p.product_id = o.product_id
GROUP BY p.category
ORDER BY p.category;
  category   | returned_no_else | returned_else_0
-------------+------------------+-----------------
 Accessories |                  |               0
 Electronics |           899.00 |          899.00
 Furniture   |                  |               0

Without ELSE, a category with no returns gets NULL (an empty cell), because SUM of nothing is NULL. With ELSE 0, it gets 0. Neither is wrong: NULL says “nothing to add up,” 0 says “the total is zero.” For reports, ELSE 0 is usually friendlier, especially if the numbers feed into more math, where NULL would spread, as shown in the NULL values lesson.

A Shortcut in PostgreSQL and SQLite: FILTER

PostgreSQL and SQLite support the standard FILTER clause, which reads a little more clearly than CASE:

SELECT p.category,
       SUM(o.quantity * p.price) FILTER (WHERE o.status = 'shipped') AS shipped,
       SUM(o.quantity * p.price) FILTER (WHERE o.status = 'pending') AS pending
FROM orders o
JOIN products p ON p.product_id = o.product_id
GROUP BY p.category
ORDER BY p.category;
  category   | shipped | pending
-------------+---------+---------
 Accessories |  165.00 |  125.00
 Electronics | 3444.00 |
 Furniture   | 1040.00 |  320.00

FILTER behaves like a CASE without ELSE, so empty combinations are NULL. MySQL and SQL Server don’t support FILTER; use CASE there.

Adding a Totals Row

A pivot report often needs a Total row at the bottom. One portable way is to UNION ALL the totals onto the grouped rows, with a hidden sort column to keep the total last:

SELECT category, shipped, other, orders
FROM (
    SELECT p.category,
           SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
           SUM(CASE WHEN o.status <> 'shipped' THEN 1 ELSE 0 END) AS other,
           COUNT(*) AS orders,
           0 AS sort_order
    FROM orders o
    JOIN products p ON p.product_id = o.product_id
    GROUP BY p.category

    UNION ALL

    SELECT 'Total',
           SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END),
           SUM(CASE WHEN status <> 'shipped' THEN 1 ELSE 0 END),
           COUNT(*),
           1
    FROM orders
) AS report
ORDER BY sort_order, category;
  category   | shipped | other | orders
-------------+---------+-------+--------
 Accessories |       2 |     1 |      3
 Electronics |       4 |     1 |      5
 Furniture   |       2 |     2 |      4
 Total       |       8 |     4 |     12

GROUP BY ROLLUP, covered in the aggregate functions lesson, can produce the same subtotal rows with less code in PostgreSQL, MySQL, and SQL Server.

SQL Server’s PIVOT Operator

SQL Server has a dedicated PIVOT operator. You give it a source query, the aggregate to calculate, and the list of values that become columns:

SELECT category, [shipped], [pending], [returned], [cancelled]
FROM (
    SELECT p.category, o.status, o.quantity * p.price AS revenue
    FROM orders o
    JOIN products p ON p.product_id = o.product_id
) AS src
PIVOT (
    SUM(revenue) FOR status IN ([shipped], [pending], [returned], [cancelled])
) AS pvt
ORDER BY category;
  category   | shipped | pending | returned | cancelled
-------------+---------+---------+----------+-----------
 Accessories |  165.00 |  125.00 |     NULL |      NULL
 Electronics | 3444.00 |    NULL |   899.00 |      NULL
 Furniture   | 1040.00 |  320.00 |     NULL |    360.00

A few things to know:

  • The source query should contain only the columns PIVOT needs: the row column, the column that becomes headers, and the value. Any extra column becomes another grouping column and splits your rows.
  • The values in IN (...) are written as column names in square brackets.
  • Empty combinations are NULL. Wrap the columns in COALESCE([pending], 0) in the outer SELECT if you want zeros.

Oracle has a very similar PIVOT. MySQL, PostgreSQL, and SQLite don’t have one, and the CASE version works in all of them.

PostgreSQL’s crosstab()

PostgreSQL’s optional tablefunc extension adds crosstab(). It takes a query that returns row, column, value in that order, plus a query listing the column values:

CREATE EXTENSION IF NOT EXISTS tablefunc;

SELECT *
FROM crosstab(
    $$SELECT p.category, o.status, SUM(o.quantity * p.price)
      FROM orders o
      JOIN products p ON p.product_id = o.product_id
      GROUP BY p.category, o.status
      ORDER BY 1, 2$$,
    $$VALUES ('shipped'), ('pending'), ('returned'), ('cancelled')$$
) AS ct(category VARCHAR, shipped NUMERIC, pending NUMERIC,
        returned NUMERIC, cancelled NUMERIC)
ORDER BY category;
  category   | shipped | pending | returned | cancelled
-------------+---------+---------+----------+-----------
 Accessories |  165.00 |  125.00 |          |
 Electronics | 3444.00 |         |   899.00 |
 Furniture   | 1040.00 |  320.00 |          |    360.00

$$ ... $$ is PostgreSQL’s way of quoting text that contains single quotes. You must list the output columns and their types in AS ct(...), and installing an extension may need admin rights. For most reports, the CASE version is simpler and needs nothing extra.

When You Don’t Know the Columns in Advance

Every method above needs the column names written into the query. If the values change, like a new status or a new month, the query must change too. SQL can’t produce a variable number of columns in a plain query.

You have two options.

Generate the query. Use SQL to write the CASE lines, then run the result. In PostgreSQL:

SELECT STRING_AGG(
         'SUM(CASE WHEN o.status = ''' || status || ''' THEN o.quantity * p.price ELSE 0 END) AS ' || status,
         ',' || CHR(10) ORDER BY status) AS column_list
FROM (SELECT DISTINCT status FROM orders) s;
SUM(CASE WHEN o.status = 'cancelled' THEN o.quantity * p.price ELSE 0 END) AS cancelled,
SUM(CASE WHEN o.status = 'pending' THEN o.quantity * p.price ELSE 0 END) AS pending,
SUM(CASE WHEN o.status = 'returned' THEN o.quantity * p.price ELSE 0 END) AS returned,
SUM(CASE WHEN o.status = 'shipped' THEN o.quantity * p.price ELSE 0 END) AS shipped

Paste the lines into the pivot query, or build and run the whole query inside a stored procedure with dynamic SQL. Only do that with values from your own tables, never with user input, or you open the door to SQL injection. Pivot outside the database. Return long data and let the report tool pivot it: Excel pivot tables, Power BI, or pivot_table() in pandas. These tools are built for a changing number of columns.

Unpivoting: Columns Back into Rows

Sometimes you get data that’s already wide, like a spreadsheet export with one column per month, and you need it long again to filter, join, or chart it. That’s an unpivot.

The portable way is one SELECT per column, stacked with UNION ALL. Here the wide table comes from a CTE, so the example runs anywhere:

WITH wide AS (
    SELECT p.category,
           SUM(CASE WHEN o.status = 'shipped' THEN o.quantity * p.price ELSE 0 END) AS shipped,
           SUM(CASE WHEN o.status = 'pending' THEN o.quantity * p.price ELSE 0 END) AS pending
    FROM orders o
    JOIN products p ON p.product_id = o.product_id
    GROUP BY p.category
)
SELECT category, 'shipped' AS status, shipped AS revenue FROM wide
UNION ALL
SELECT category, 'pending', pending FROM wide
ORDER BY category, status;
  category   | status  | revenue
-------------+---------+---------
 Accessories | pending |  125.00
 Accessories | shipped |  165.00
 Electronics | pending |       0
 Electronics | shipped | 3444.00
 Furniture   | pending |  320.00
 Furniture   | shipped | 1040.00

Each SELECT turns one column into rows, with a literal ('shipped', 'pending') recording which column it came from. The column names of the result come from the first SELECT, as explained in the UNION lesson.

SQL Server also has an UNPIVOT operator that does the same with less repetition:

WITH wide AS (
    SELECT p.category,
           SUM(CASE WHEN o.status = 'shipped' THEN o.quantity * p.price ELSE 0 END) AS shipped,
           SUM(CASE WHEN o.status = 'pending' THEN o.quantity * p.price ELSE 0 END) AS pending
    FROM orders o
    JOIN products p ON p.product_id = o.product_id
    GROUP BY p.category
)
SELECT category, status, revenue
FROM wide
UNPIVOT (revenue FOR status IN (shipped, pending)) AS u
ORDER BY category, status;

It returns the same six rows. One difference: UNPIVOT skips NULL values, while the UNION ALL version keeps them.

Common Mistakes to Avoid

  • Grouping by the column you’re pivoting. If you GROUP BY category, status, each status still gets its own row. Group only by the row column; the CASE expressions handle the rest.
  • Forgetting the aggregate. CASE WHEN status = 'shipped' THEN revenue END without SUM (or MAX, COUNT) returns one value per original row, not one per group, and most databases reject it.
  • Mixing up SUM and COUNT. COUNT(CASE ... THEN 1 ELSE 0 END) counts every row, because 0 isn’t NULL. Use SUM with ELSE 0, or COUNT with no ELSE.
  • Misspelled values. WHEN status = 'Shipped' matches nothing if the data says shipped, and the column quietly fills with zeros. Check the exact values with SELECT DISTINCT first.
  • Extra columns in SQL Server’s PIVOT source. Keep the source query to exactly the row column, the header column, and the value.
  • Filtering with WHERE on a pivoted column. Pivoted columns don’t exist until after grouping. Filter them with HAVING (repeating the SUM(CASE ...) expression), or wrap the pivot in a CTE and filter outside it with WHERE.

Frequently Asked Questions

Does MySQL have a PIVOT function?

No. MySQL, PostgreSQL, and SQLite don’t have a PIVOT operator. Use SUM(CASE WHEN ... END) with GROUP BY, which works in every database.

What is the difference between PIVOT and GROUP BY?

GROUP BY returns one row per combination of values (long data). A pivot also groups, but spreads one of those values across columns (wide data). In SQL, a pivot is a GROUP BY plus one conditional aggregate per column.

Can SQL pivot a dynamic number of columns?

Not in a plain query. You either generate the query text first and run it (dynamic SQL), or return long data and pivot in a tool like Excel, Power BI, or pandas.

What is unpivoting used for?

Turning wide data, like one column per month, back into rows so you can filter, join, sort, and chart it. Most analysis is easier on long data.

Conclusion

Pivoting turns long, one-row-per-fact data into the wide tables people expect in reports. The method that works everywhere is GROUP BY the row column plus one SUM(CASE WHEN ... END) per output column; use ELSE 0 for zeros, COUNT or SUM of ones for counts, and UNION ALL for a totals row. SQL Server’s PIVOT and PostgreSQL’s crosstab() are shortcuts for the same idea, and UNION ALL or UNPIVOT turns columns back into rows.

Next in the Learn SQL series, you’ll calculate running totals and rankings without collapsing rows, with SQL Window Functions.