Snowflake SQL Tutorial 59 - PIVOT in Snowflake - Rows Into Columns - and the One Mistake That Turns 8 Rows Into 41

Snowflake SQL · Episode 59

In this post we are going to cover PIVOT in Snowflake.

PIVOT turns one column’s values into column names, aggregating as it goes. We start with a long, thin result that has one row per customer and status, and we end up with a wide one that has one row per customer and a column for each status. It is four lines of SQL.

We will start with the shape we are leaving, then write the pivot, then fix the ugly headers it gives us. After that we will make the one mistake almost everybody makes, and watch an eight-row answer turn into a forty-one-row one. Then the empty cells, the aggregate that decides what empty looks like, two ways to stop typing the IN list by hand, and the error message that points at the wrong word.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back, including the error message.

Episode 59 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

Everything on this page runs against the shared ORDERS table. Run this once if you have not already.

Sample data — ORDERS
-- ORDERS and CUSTOMERS come from the shared sample-data script. Every episode
-- in this series reuses the same tables, so you only set them up once.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE ORDERS (
    ORDER_ID     INT,
    CUSTOMER_ID  INT,
    ORDER_DATE   DATE,
    SHIP_DATE    DATE,
    STATUS       VARCHAR,
    AMOUNT       NUMBER(10,2),
    QUANTITY     INT
);

INSERT INTO ORDERS VALUES
    (1001, 101, '2023-01-12', '2023-01-15', 'SHIPPED',   4200.00,  12),
    (1002, 102, '2023-01-28', '2023-02-02', 'SHIPPED',    890.50,   3),
    (1003, 101, '2023-02-14', '2023-02-16', 'SHIPPED',   6150.00,  20),
    (1004, 103, '2023-02-27', NULL,         'CANCELLED', 1500.00,   5),
    (1005, 104, '2023-03-09', '2023-03-14', 'SHIPPED',   2310.75,   8),
    (1006, 101, '2023-03-22', '2023-03-24', 'SHIPPED',   5020.00,  16),
    (1007, 105, '2023-04-05', '2023-04-11', 'SHIPPED',   7890.00,  25),
    (1008, 102, '2023-04-19', '2023-04-23', 'SHIPPED',   1120.00,   4),
    (1009, 103, '2023-05-02', '2023-05-06', 'SHIPPED',   3340.25,  11),
    (1010, 106, '2023-05-21', NULL,         'PENDING',    640.00,   2),
    (1011, 101, '2023-06-08', '2023-06-10', 'SHIPPED',   8100.00,  27),
    (1012, 104, '2023-06-25', '2023-06-30', 'SHIPPED',   1975.50,   7),
    (1013, 105, '2023-07-11', '2023-07-15', 'SHIPPED',   6420.00,  21),
    (1014, 102, '2023-07-29', '2023-08-03', 'RETURNED',   750.00,   3),
    (1015, 107, '2023-08-14', '2023-08-17', 'SHIPPED',   9250.00,  30),
    (1016, 103, '2023-08-30', '2023-09-04', 'SHIPPED',   2860.00,   9),
    (1017, 101, '2023-09-16', '2023-09-19', 'SHIPPED',   5540.00,  18),
    (1018, 106, '2023-10-03', '2023-10-08', 'SHIPPED',   1430.00,   5),
    (1019, 105, '2023-10-22', '2023-10-26', 'SHIPPED',   7015.00,  23),
    (1020, 107, '2023-11-07', '2023-11-10', 'SHIPPED',  10400.00,  34),
    (1021, 102, '2023-11-24', '2023-11-29', 'SHIPPED',    980.00,   4),
    (1022, 104, '2023-12-09', NULL,         'CANCELLED', 2250.00,   8),
    (1023, 101, '2023-12-27', '2023-12-30', 'SHIPPED',   6730.00,  22),
    (1024, 103, '2024-01-15', '2024-01-18', 'SHIPPED',   3910.00,  13),
    (1025, 107, '2024-01-31', '2024-02-05', 'SHIPPED',  11200.00,  36),
    (1026, 105, '2024-02-17', '2024-02-21', 'SHIPPED',   8340.00,  27),
    (1027, 106, '2024-03-04', '2024-03-09', 'SHIPPED',   1690.00,   6),
    (1028, 102, '2024-03-21', '2024-03-25', 'SHIPPED',   1240.00,   5),
    (1029, 101, '2024-04-06', '2024-04-09', 'SHIPPED',   7460.00,  24),
    (1030, 109, '2024-04-23', '2024-04-28', 'SHIPPED',   5180.00,  17),
    (1031, 103, '2024-05-10', '2024-05-14', 'SHIPPED',   4025.00,  14),
    (1032, 107, '2024-05-28', '2024-06-01', 'SHIPPED',  12850.00,  41),
    (1033, 105, '2024-06-13', NULL,         'PENDING',   6900.00,  22),
    (1034, 109, '2024-06-30', '2024-07-04', 'SHIPPED',   4760.00,  16),
    (1035, 101, '2024-07-18', '2024-07-21', 'SHIPPED',   8820.00,  29),
    (1036, 104, '2024-08-02', '2024-08-07', 'SHIPPED',   2540.00,   9),
    (1037, 107, '2024-08-25', '2024-08-29', 'SHIPPED',  13100.00,  43),
    (1038, 109, '2024-09-11', '2024-09-15', 'SHIPPED',   5930.00,  19),
    (1039, 102, '2024-09-29', '2024-10-03', 'RETURNED',  1080.00,   4),
    (1040, 101, '2024-10-16', '2024-10-19', 'SHIPPED',   9640.00,  31);

-- One deliberate NULL amount, inserted on its own so it is easy to see why it
-- is there. It makes COUNT(*), COUNT(AMOUNT) and SUM(AMOUNT) give three
-- different answers, and it turns up twice on this page.
INSERT INTO ORDERS VALUES
    (1041, 106, '2024-11-05', NULL, 'PENDING', NULL, 3);

Level 6 is about reshaping. The same numbers, arranged differently. So before we pivot anything, let's look at the arrangement we are leaving. It is a plain GROUP BY, with nothing new in it at all.

Query — total amount per customer, per status
SELECT CUSTOMER_ID, STATUS, SUM(AMOUNT) AS TOTAL, COUNT(*) AS N_ORDERS
FROM ORDERS
GROUP BY CUSTOMER_ID, STATUS
ORDER BY CUSTOMER_ID, STATUS;
Result13 rows · 4 columns
CUSTOMER_IDSTATUSTOTALN_ORDERS
101SHIPPED61660.009
102RETURNED1830.002
102SHIPPED4230.504
103CANCELLED1500.001
103SHIPPED14135.254
104CANCELLED2250.001
104SHIPPED6826.253
105PENDING6900.001
105SHIPPED29665.004
106PENDING640.002
106SHIPPED3120.002
107SHIPPED56800.005
109SHIPPED15870.003

Thirteen rows, going down the screen. One row per customer-and-status combination that exists, with a total and an order count beside it. This is called long form, and it is the shape almost every aggregate query produces.

That thirteen is worth a second of attention before we reshape it, so let's count the parts separately.

Query
SELECT COUNT(*) AS LONG_FORM_ROWS,
       COUNT(DISTINCT CUSTOMER_ID) AS CUSTOMERS,
       COUNT(DISTINCT STATUS) AS STATUSES
FROM (SELECT CUSTOMER_ID, STATUS FROM ORDERS GROUP BY CUSTOMER_ID, STATUS);
Result1 row · 3 columns
LONG_FORM_ROWSCUSTOMERSSTATUSES
1384

Eight customers and four statuses. Multiply those and there are 8 * 4, so 32, combinations that could exist, of which 13 actually do. Read the long form down and you will see why. No customer here has orders in more than two of the four statuses.

Remember this number

That gap between 13 and 32 is not a data quality problem. It is what normal data looks like. It matters here because a pivot lays out the full grid, every customer against every status, so the combinations that do not exist have to be represented by something. What that something is turns out to be the subject of two sections of this page.

What we want is those thirteen rows rearranged into eight rows going across. One row per customer, one column per status.

Let's write the pivot

Here is the whole statement, with the moving parts named.

The shape of it
-- The shape of the statement, with the four parts named.
SELECT *
FROM (<row key>, <column key>, <value>)        -- narrow the input to THREE columns
PIVOT (
    <aggregate>(<value>)                        -- how to combine the values
    FOR <column key> IN (<list of values>)      -- which values become columns
)
ORDER BY <row key>;

Three things go in and PIVOT needs all three. The row key, which is what each output row represents. The column key, which is the column whose values become headers. And the value, which is what gets aggregated into each cell. Filled in, that is four lines of real SQL.

Query
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_ID'SHIPPED''PENDING''CANCELLED''RETURNED'
10161660.00NULLNULLNULL
1024230.50NULLNULL1830.00
10314135.25NULL1500.00NULL
1046826.25NULL2250.00NULL
10529665.006900.00NULLNULL
1063120.00640.00NULLNULL
10756800.00NULLNULLNULL
10915870.00NULLNULLNULL

Eight rows, one per customer, and the four statuses are now columns. Same numbers as the long form, different shape. Customer 103’s 14135.25 and 1500.00 were two separate rows in the long form and they are one row here.

One thing is wrong with it. Look at the headers

The column names came back as 'SHIPPED', 'PENDING' and so on, with the quote marks in them. That is not a display artefact. The column’s name literally is the string literal from the IN list, quotes included, which makes it a nuisance to reference from anything downstream.

The fix is to alias the whole pivoted result and name its columns positionally. The row key first, then one name per IN-list value, in the same order.

Query
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
  AS P (CUSTOMER_ID, SHIPPED, PENDING, CANCELLED, RETURNED)
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_IDSHIPPEDPENDINGCANCELLEDRETURNED
10161660.00NULLNULLNULL
1024230.50NULLNULL1830.00
10314135.25NULL1500.00NULL
1046826.25NULL2250.00NULL
10529665.006900.00NULLNULL
1063120.00640.00NULLNULL
10756800.00NULLNULLNULL
10915870.00NULLNULLNULL

Same eight rows, same numbers, and headers we can actually use in a view or a SELECT list. Alias the output every time. It costs one clause, and it is the difference between a pivot you can build on and one you have to quote around for ever.

Now let's make the one mistake everybody makes

This is worth seeing as a number rather than hearing as advice. That subquery in the FROM clause looks like ceremony. Dropping it and pivoting the table directly is shorter, tidier, and reads better. So let's drop it.

Query — no subquery, pivoting ORDERS directly
SELECT *
FROM ORDERS
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
ORDER BY ORDER_ID
LIMIT 12;
Result12 rows · 9 columns · scroll →
The query carries its own LIMIT 12, so this grid is the first twelve rows. How many there are in total is the next query in this section.
ORDER_IDCUSTOMER_IDORDER_DATESHIP_DATEQUANTITY'SHIPPED''PENDING''CANCELLED''RETURNED'
10011012023-01-122023-01-15124200.00NULLNULLNULL
10021022023-01-282023-02-023890.50NULLNULLNULL
10031012023-02-142023-02-16206150.00NULLNULLNULL
10041032023-02-27NULL5NULLNULL1500.00NULL
10051042023-03-092023-03-1482310.75NULLNULLNULL
10061012023-03-222023-03-24165020.00NULLNULLNULL
10071052023-04-052023-04-11257890.00NULLNULLNULL
10081022023-04-192023-04-2341120.00NULLNULLNULL
10091032023-05-022023-05-06113340.25NULLNULLNULL
10101062023-05-21NULL2NULL640.00NULLNULL
10111012023-06-082023-06-10278100.00NULLNULLNULL
10121042023-06-252023-06-3071975.50NULLNULLNULL

Something has clearly gone wrong, and the column headers say exactly what. ORDER_ID, CUSTOMER_ID, ORDER_DATE, SHIP_DATE and QUANTITY are all still there, followed by the four pivoted columns. STATUS and AMOUNT are the only two that went away.

That is the whole explanation, and it is a rule worth memorising. PIVOT consumes exactly two columns, and silently groups by every single one of the others.

Column of ORDERSWhat PIVOT does with it
STATUSConsumed — named in FOR, so its values become the new column headers
AMOUNTConsumed — the argument of the aggregate, so its values become the cells
ORDER_IDSurvives, and joins the implicit grouping key
CUSTOMER_IDSurvives, and joins the implicit grouping key
ORDER_DATESurvives, and joins the implicit grouping key
SHIP_DATESurvives, and joins the implicit grouping key
QUANTITYSurvives, and joins the implicit grouping key

That leaves five columns in the grouping key, and one of them is ORDER_ID, which is unique for every row. A unique column in the grouping key means every group holds exactly one order. So instead of one row per customer we get one row per order, and the four pivoted columns hold at most one number each. The one status that order actually has, with the rest NULL.

That is measurable, so let's measure it rather than describe it.

Query — both versions counted, against the table itself
SELECT
  (SELECT COUNT(*) FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
     PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED','PENDING','CANCELLED','RETURNED')))
     AS ROWS_WHEN_NARROWED,
  (SELECT COUNT(*) FROM ORDERS
     PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED','PENDING','CANCELLED','RETURNED')))
     AS ROWS_WHEN_NOT_NARROWED,
  (SELECT COUNT(DISTINCT CUSTOMER_ID) FROM ORDERS) AS CUSTOMERS,
  (SELECT COUNT(*) FROM ORDERS) AS ORDERS_TOTAL;
Result1 row · 4 columns
ROWS_WHEN_NARROWEDROWS_WHEN_NOT_NARROWEDCUSTOMERSORDERS_TOTAL
841841

8 rows when the input is narrowed and 41 when it is not, sitting next to 8 customers and 41 orders. Those numbers are not a coincidence and they are not approximate. The narrowed pivot produces one row per customer, and the un-narrowed one produces one row per order.

The rule

The subquery is not ceremony. It is the statement. PIVOT has no syntax for group by these columns. It decides the grouping entirely from what you hand it. So the input must contain exactly three columns: the row key, the column key and the value, and nothing else. Any extra column silently makes the output finer-grained, and the only symptom is a row count that is bigger than it should be.

Why nobody catches it by reading

This is also why the broken version is so easy to miss in review. It does not error, it does not warn, and on a table where the surviving columns happen not to be unique it returns almost the right shape. Count the rows against what you expect, the way the counting query does, and you will never be fooled by it.

What happens to a value we leave out of the IN list?

The IN list decides which columns we get. So what happens to a value we leave out of it? Let's run the same pivot with 'RETURNED' removed, three statuses instead of four.

Query
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED'))
  AS P (CUSTOMER_ID, SHIPPED, PENDING, CANCELLED)
ORDER BY CUSTOMER_ID;
Result8 rows · 4 columns
CUSTOMER_IDSHIPPEDPENDINGCANCELLED
10161660.00NULLNULL
1024230.50NULLNULL
10314135.25NULL1500.00
1046826.25NULL2250.00
10529665.006900.00NULL
1063120.00640.00NULL
10756800.00NULLNULL
10915870.00NULLNULL

Still eight rows. Still one row per customer. The grid looks entirely healthy, and that is the problem. Customer 102’s returned orders have gone. Not folded into another column, not reported anywhere. Dropped, with nothing in the result to say so.

In real life nobody has the four-status pivot in front of them to compare against. So let's measure the loss directly instead.

Query — what the IN list cost you
SELECT
  (SELECT SUM(AMOUNT) FROM ORDERS) AS ALL_ORDERS,
  (SELECT SUM(AMOUNT) FROM ORDERS WHERE STATUS <> 'RETURNED') AS WITHOUT_RETURNED,
  (SELECT SUM(AMOUNT) FROM ORDERS WHERE STATUS = 'RETURNED') AS RETURNED_ONLY;
Result1 row · 3 columns
ALL_ORDERSWITHOUT_RETURNEDRETURNED_ONLY
205427.00203597.001830.00

205427.00 across all orders, 203597.00 once the returned ones are excluded, and the difference is exactly the 1830.00 in the third column. That is the same figure as customer 102’s RETURNED cell in the four-status pivot.

So the defence is simple. Never write the IN list from memory. Ask the table what values exist first.

Query — what is actually in the column
SELECT STATUS, COUNT(*) AS N_ORDERS, SUM(AMOUNT) AS TOTAL
FROM ORDERS
GROUP BY STATUS
ORDER BY STATUS;
Result4 rows · 3 columns
STATUSN_ORDERSTOTAL
CANCELLED23750.00
PENDING37540.00
RETURNED21830.00
SHIPPED34192307.00
This one has no symptom at all

A pivot with an incomplete IN list is a report that quietly understates its own totals, and the row count does not change, so no sanity check based on row counts will catch it. Check the list against a SELECT DISTINCT on the column key every time. And if the set of values can grow, use one of the dynamic forms we come to later instead.

Now let's look at those empty cells

Back to the aliased pivot with all four statuses in it. Most of its grid is empty, and what fills those empty cells matters as soon as anything downstream does arithmetic on them. They are NULL. Rather than take that from the look of the grid, let's count them.

Query — COUNT ignores NULLs, so it counts what is really there
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT(SHIPPED)   AS NON_NULL_SHIPPED,
       COUNT(PENDING)   AS NON_NULL_PENDING,
       COUNT(CANCELLED) AS NON_NULL_CANCELLED,
       COUNT(RETURNED)  AS NON_NULL_RETURNED
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED','PENDING','CANCELLED','RETURNED'))
  AS P (CUSTOMER_ID, SHIPPED, PENDING, CANCELLED, RETURNED);
Result1 row · 5 columns
ROWS_TOTALNON_NULL_SHIPPEDNON_NULL_PENDINGNON_NULL_CANCELLEDNON_NULL_RETURNED
88221

Eight rows in the pivot. 8 non-empty SHIPPED cells, 2 PENDING, 2 CANCELLED and 1 RETURNED.

Add those four up and we get 13, which is exactly the row count of the long form we started from. Every long-form row became one non-empty cell, and every combination that never existed became a NULL. The two shapes hold the same information, and that arithmetic is the proof of it.

If we would rather have zeros, PIVOT has a clause for it.

Query — with DEFAULT ON NULL
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED')
       DEFAULT ON NULL (0))
  AS P (CUSTOMER_ID, SHIPPED, PENDING, CANCELLED, RETURNED)
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_IDSHIPPEDPENDINGCANCELLEDRETURNED
10161660.000.000.000.00
1024230.500.000.001830.00
10314135.250.001500.000.00
1046826.250.002250.000.00
10529665.006900.000.000.00
1063120.00640.000.000.00
10756800.000.000.000.00
10915870.000.000.000.00

Same grid, with 0.00 where the NULLs were. DEFAULT ON NULL (0) goes inside the PIVOT clause, straight after the IN list.

Before you reach for DEFAULT ON NULL

Zeros are not always the honest choice. No cancelled orders and cancelled orders totalling nothing are two different statements, and a NULL tells them apart while a 0.00 does not. Use DEFAULT ON NULL when a downstream consumer cannot handle NULLs, not as a tidying habit.

Now let's change the aggregate to COUNT

Here is a contrast worth carrying away. Same pivot, same narrowed input, same IN list, with COUNT instead of SUM.

Query
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (COUNT(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
  AS P (CUSTOMER_ID, N_SHIPPED, N_PENDING, N_CANCELLED, N_RETURNED)
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_IDN_SHIPPEDN_PENDINGN_CANCELLEDN_RETURNED
1019000
1024002
1034010
1043010
1054100
1062100
1075000
1093000

The empty cells came back as 0 this time, with no DEFAULT ON NULL anywhere in the query. Nothing about PIVOT changed. The difference is in the aggregate. COUNT of no rows is genuinely zero, while SUM of no rows is genuinely NULL. The pivot is simply reporting what its aggregate returned for an empty group.

So before we write DEFAULT ON NULL, let's check whether our aggregate was ever going to produce a NULL in the first place. COUNT will not. SUM, MIN, MAX and AVG all will.

COUNT(AMOUNT) is not COUNT(*)

One subtlety in this grid, because it is the kind of thing that gets read wrong. The aggregate here is COUNT(AMOUNT), not COUNT(*), so it counts orders that have an amount. Customer 106 shows N_PENDING 1, while the long form gives that same customer and status an N_ORDERS of 2. Both are right. One of those two pending orders has no AMOUNT, which is the row inserted on its own at the end of the sample-data script, and COUNT(AMOUNT) skips it while COUNT(*) does not. An empty cell and a cell counting only the non-NULL values look identical in a pivot.

And one reassuring check. Add the N_SHIPPED column down and it comes to 34, which is the SHIPPED count in the status grid we ran to check the IN list. The reshaping lost nothing.

Can we avoid typing the IN list at all?

Writing out every value by hand is tedious, and worse, it is the thing that goes stale when a new status appears. There are two forms that ask the data instead. The first one lets Snowflake find the distinct values itself.

Query — IN (ANY ORDER BY STATUS)
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN (ANY ORDER BY STATUS))
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_ID'CANCELLED''PENDING''RETURNED''SHIPPED'
101NULLNULLNULL61660.00
102NULLNULL1830.004230.50
1031500.00NULLNULL14135.25
1042250.00NULLNULL6826.25
105NULL6900.00NULL29665.00
106NULL640.00NULL3120.00
107NULLNULLNULL56800.00
109NULLNULLNULL15870.00

Eight rows again, the same numbers again. But look at the column order. It is now 'CANCELLED', 'PENDING', 'RETURNED', 'SHIPPED'. Alphabetical, because that is what ORDER BY STATUS inside the ANY asked for.

The second form is a subquery, and it does the same job.

Query — IN (SELECT DISTINCT ...)
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN (SELECT DISTINCT STATUS FROM ORDERS ORDER BY STATUS))
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_ID'CANCELLED''PENDING''RETURNED''SHIPPED'
101NULLNULLNULL61660.00
102NULLNULL1830.004230.50
1031500.00NULLNULL14135.25
1042250.00NULLNULL6826.25
105NULL6900.00NULL29665.00
106NULL640.00NULL3120.00
107NULLNULLNULL56800.00
109NULLNULLNULL15870.00

Identical output. Pick whichever reads better to you. Neither one is more correct than the other.

What the dynamic forms cost

The trade is that you no longer control the column order, and you cannot alias the columns positionally either. That is why both of these grids have quoted headers. You cannot write a positional alias list for a set of columns you do not know in advance. So a hand-written IN list gives you clean, ordered, predictable headers, and a dynamic one gives you resilience to new values. Decide which you need. You cannot have both in one statement.

Which one, in practice

This is the deciding factor more often than it looks. A pivot feeding a chart or a downstream view wants fixed, named, ordered columns, so write the list out and check it against a DISTINCT query. A pivot you are running just to look at something wants ANY, because you do not care what the headers are called.

Now let's put quarters across the top instead

Nothing we have done is specific to a status column. The column key can be any expression. So let's put quarters across the top instead, built by gluing the quarter and the year into a string in the subquery before the pivot ever sees it.

Query
SELECT *
FROM (SELECT CUSTOMER_ID,
             'Q' || QUARTER(ORDER_DATE) || '-' || YEAR(ORDER_DATE) AS QTR,
             AMOUNT
      FROM ORDERS
      WHERE YEAR(ORDER_DATE) = 2024)
PIVOT (SUM(AMOUNT) FOR QTR IN ('Q1-2024', 'Q2-2024', 'Q3-2024', 'Q4-2024'))
  AS P (CUSTOMER_ID, Q1, Q2, Q3, Q4)
ORDER BY CUSTOMER_ID;
Result8 rows · 5 columns
CUSTOMER_IDQ1Q2Q3Q4
101NULL7460.008820.009640.00
1021240.00NULL1080.00NULL
1033910.004025.00NULLNULL
104NULLNULL2540.00NULL
1058340.006900.00NULLNULL
1061690.00NULLNULLNULL
10711200.0012850.0013100.00NULL
109NULL9940.005930.00NULL

The subquery is still exactly three columns. CUSTOMER_ID as the row key, the computed QTR string as the column key, and AMOUNT as the value. The rule about three columns does not relax just because one of them is calculated.

And because a crosstab is exactly the sort of thing nobody checks, let's work out the same totals the long way.

Query
SELECT 'Q' || QUARTER(ORDER_DATE) || '-' || YEAR(ORDER_DATE) AS QTR,
       COUNT(*) AS N_ORDERS, SUM(AMOUNT) AS TOTAL
FROM ORDERS
WHERE YEAR(ORDER_DATE) = 2024
GROUP BY 1
ORDER BY 1;
Result4 rows · 3 columns
QTRN_ORDERSTOTAL
Q1-2024526380.00
Q2-2024641175.00
Q3-2024531470.00
Q4-202429640.00

Add each pivoted column downwards and we get that grid’s TOTAL column, quarter for quarter. 26380.00 for Q1-2024, and the same agreement for the other three. The reshape moved the numbers without changing any of them.

One cell that is empty for a different reason

Q4-2024 is counted as two orders in the check grid but shows only one number in the pivot. That is the NULL amount from the sample-data script again. It is a real order in a real quarter, and SUM of a single NULL is NULL, so its cell stays empty. Worth knowing before you explain a blank cell as missing data.

One last thing: the error that points at the wrong word

You will meet this message, and it will not help you. PIVOT’s first argument has to be an aggregate function call. Let's see what happens with a bare column instead.

Query
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (AMOUNT FOR STATUS IN ('SHIPPED', 'PENDING'))
ORDER BY CUSTOMER_ID;
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 3 at position 14 unexpected 'FOR'.
syntax error line 3 at position 18 unexpected 'STATUS'.

Read the message. It does not say you need an aggregate. It points at FOR, and then at STATUS, and neither of those is the problem.

That is a parser message rather than a semantic one. The grammar of the PIVOT clause expects a function call in that position. So when it finds a plain column name the clause never matches, and the parser reports the first token it could not account for, which is the FOR immediately afterwards.

The rule of thumb

So when Snowflake tells you it did not expect FOR, check the aggregate first. A missing SUM, COUNT or MAX around the value column is nearly always the cause, and no part of the message will mention it.

Key points

  • PIVOT turns one column's values into column names, aggregating the value column into each cell. The input needs exactly three columns: row key, column key, value.
  • PIVOT consumes the column named in FOR and the column inside the aggregate, then groups by every other column it was given. There is no syntax to tell it otherwise.
  • Leave the narrowing subquery out and the surviving columns join the grouping key. A unique one like ORDER_ID gives you one row per source row instead of one per group. On this data that is the difference between 8 rows and 41.
  • Unaliased pivot columns are named after the string literals, quote marks included. Alias the result positionally: row key first, then one name per IN-list value.
  • A value missing from the IN list is dropped, not folded elsewhere, and the row count does not change. So check the list against a SELECT DISTINCT every time.
  • Empty cells are whatever the aggregate returns for an empty group: NULL for SUM, 0 for COUNT. DEFAULT ON NULL overrides the first case and is not needed for the second.
  • IN (ANY ORDER BY ...) and IN (SELECT DISTINCT ...) find the values for you, at the cost of controlling the column order and of being able to alias the columns at all.
  • The column key can be a computed expression, so a pivot is not limited to the columns a table happens to store.
  • A bare column where the aggregate belongs produces a syntax error pointing at FOR. It is not about FOR. Check the aggregate.
Next in this series

In the next post we will cover UNPIVOT, which is the same operation backwards. Columns collapsed into rows, which is how we get a wide report back into the long form that everything else in SQL prefers to work with.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode, including the failed query and its error message. The ORDERS data is invented demo data created by the sample-data script on this page, and the amounts carry no currency. No performance or benchmark claims are made anywhere in this series — in particular, nothing here was timed against a CASE-based crosstab. Clause behaviour follows the Snowflake PIVOT documentation and the aggregate function reference.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.