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
- Let's write the pivot
- Now let's make the one mistake everybody makes
- What happens to a value we leave out of the IN list?
- Now let's look at those empty cells
- Now let's change the aggregate to COUNT
- Can we avoid typing the IN list at all?
- Now let's put quarters across the top instead
- One last thing: the error that points at the wrong word
Let's create some sample data
Everything on this page runs against the shared ORDERS table. Run this once if you have not already.
-- 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.
SELECT CUSTOMER_ID, STATUS, SUM(AMOUNT) AS TOTAL, COUNT(*) AS N_ORDERS
FROM ORDERS
GROUP BY CUSTOMER_ID, STATUS
ORDER BY CUSTOMER_ID, STATUS;| CUSTOMER_ID | STATUS | TOTAL | N_ORDERS |
|---|---|---|---|
| 101 | SHIPPED | 61660.00 | 9 |
| 102 | RETURNED | 1830.00 | 2 |
| 102 | SHIPPED | 4230.50 | 4 |
| 103 | CANCELLED | 1500.00 | 1 |
| 103 | SHIPPED | 14135.25 | 4 |
| 104 | CANCELLED | 2250.00 | 1 |
| 104 | SHIPPED | 6826.25 | 3 |
| 105 | PENDING | 6900.00 | 1 |
| 105 | SHIPPED | 29665.00 | 4 |
| 106 | PENDING | 640.00 | 2 |
| 106 | SHIPPED | 3120.00 | 2 |
| 107 | SHIPPED | 56800.00 | 5 |
| 109 | SHIPPED | 15870.00 | 3 |
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.
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);| LONG_FORM_ROWS | CUSTOMERS | STATUSES |
|---|---|---|
| 13 | 8 | 4 |
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.
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 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.
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
ORDER BY CUSTOMER_ID;| CUSTOMER_ID | 'SHIPPED' | 'PENDING' | 'CANCELLED' | 'RETURNED' |
|---|---|---|---|---|
| 101 | 61660.00 | NULL | NULL | NULL |
| 102 | 4230.50 | NULL | NULL | 1830.00 |
| 103 | 14135.25 | NULL | 1500.00 | NULL |
| 104 | 6826.25 | NULL | 2250.00 | NULL |
| 105 | 29665.00 | 6900.00 | NULL | NULL |
| 106 | 3120.00 | 640.00 | NULL | NULL |
| 107 | 56800.00 | NULL | NULL | NULL |
| 109 | 15870.00 | NULL | NULL | NULL |
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.
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;| CUSTOMER_ID | SHIPPED | PENDING | CANCELLED | RETURNED |
|---|---|---|---|---|
| 101 | 61660.00 | NULL | NULL | NULL |
| 102 | 4230.50 | NULL | NULL | 1830.00 |
| 103 | 14135.25 | NULL | 1500.00 | NULL |
| 104 | 6826.25 | NULL | 2250.00 | NULL |
| 105 | 29665.00 | 6900.00 | NULL | NULL |
| 106 | 3120.00 | 640.00 | NULL | NULL |
| 107 | 56800.00 | NULL | NULL | NULL |
| 109 | 15870.00 | NULL | NULL | NULL |
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.
SELECT *
FROM ORDERS
PIVOT (SUM(AMOUNT) FOR STATUS IN ('SHIPPED', 'PENDING', 'CANCELLED', 'RETURNED'))
ORDER BY ORDER_ID
LIMIT 12;| ORDER_ID | CUSTOMER_ID | ORDER_DATE | SHIP_DATE | QUANTITY | 'SHIPPED' | 'PENDING' | 'CANCELLED' | 'RETURNED' |
|---|---|---|---|---|---|---|---|---|
| 1001 | 101 | 2023-01-12 | 2023-01-15 | 12 | 4200.00 | NULL | NULL | NULL |
| 1002 | 102 | 2023-01-28 | 2023-02-02 | 3 | 890.50 | NULL | NULL | NULL |
| 1003 | 101 | 2023-02-14 | 2023-02-16 | 20 | 6150.00 | NULL | NULL | NULL |
| 1004 | 103 | 2023-02-27 | NULL | 5 | NULL | NULL | 1500.00 | NULL |
| 1005 | 104 | 2023-03-09 | 2023-03-14 | 8 | 2310.75 | NULL | NULL | NULL |
| 1006 | 101 | 2023-03-22 | 2023-03-24 | 16 | 5020.00 | NULL | NULL | NULL |
| 1007 | 105 | 2023-04-05 | 2023-04-11 | 25 | 7890.00 | NULL | NULL | NULL |
| 1008 | 102 | 2023-04-19 | 2023-04-23 | 4 | 1120.00 | NULL | NULL | NULL |
| 1009 | 103 | 2023-05-02 | 2023-05-06 | 11 | 3340.25 | NULL | NULL | NULL |
| 1010 | 106 | 2023-05-21 | NULL | 2 | NULL | 640.00 | NULL | NULL |
| 1011 | 101 | 2023-06-08 | 2023-06-10 | 27 | 8100.00 | NULL | NULL | NULL |
| 1012 | 104 | 2023-06-25 | 2023-06-30 | 7 | 1975.50 | NULL | NULL | NULL |
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 ORDERS | What PIVOT does with it |
|---|---|
STATUS | Consumed — named in FOR, so its values become the new column headers |
AMOUNT | Consumed — the argument of the aggregate, so its values become the cells |
ORDER_ID | Survives, and joins the implicit grouping key |
CUSTOMER_ID | Survives, and joins the implicit grouping key |
ORDER_DATE | Survives, and joins the implicit grouping key |
SHIP_DATE | Survives, and joins the implicit grouping key |
QUANTITY | Survives, 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.
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;| ROWS_WHEN_NARROWED | ROWS_WHEN_NOT_NARROWED | CUSTOMERS | ORDERS_TOTAL |
|---|---|---|---|
| 8 | 41 | 8 | 41 |
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 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.
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.
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;| CUSTOMER_ID | SHIPPED | PENDING | CANCELLED |
|---|---|---|---|
| 101 | 61660.00 | NULL | NULL |
| 102 | 4230.50 | NULL | NULL |
| 103 | 14135.25 | NULL | 1500.00 |
| 104 | 6826.25 | NULL | 2250.00 |
| 105 | 29665.00 | 6900.00 | NULL |
| 106 | 3120.00 | 640.00 | NULL |
| 107 | 56800.00 | NULL | NULL |
| 109 | 15870.00 | NULL | NULL |
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.
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;| ALL_ORDERS | WITHOUT_RETURNED | RETURNED_ONLY |
|---|---|---|
| 205427.00 | 203597.00 | 1830.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.
SELECT STATUS, COUNT(*) AS N_ORDERS, SUM(AMOUNT) AS TOTAL
FROM ORDERS
GROUP BY STATUS
ORDER BY STATUS;| STATUS | N_ORDERS | TOTAL |
|---|---|---|
| CANCELLED | 2 | 3750.00 |
| PENDING | 3 | 7540.00 |
| RETURNED | 2 | 1830.00 |
| SHIPPED | 34 | 192307.00 |
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.
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);| ROWS_TOTAL | NON_NULL_SHIPPED | NON_NULL_PENDING | NON_NULL_CANCELLED | NON_NULL_RETURNED |
|---|---|---|---|---|
| 8 | 8 | 2 | 2 | 1 |
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.
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;| CUSTOMER_ID | SHIPPED | PENDING | CANCELLED | RETURNED |
|---|---|---|---|---|
| 101 | 61660.00 | 0.00 | 0.00 | 0.00 |
| 102 | 4230.50 | 0.00 | 0.00 | 1830.00 |
| 103 | 14135.25 | 0.00 | 1500.00 | 0.00 |
| 104 | 6826.25 | 0.00 | 2250.00 | 0.00 |
| 105 | 29665.00 | 6900.00 | 0.00 | 0.00 |
| 106 | 3120.00 | 640.00 | 0.00 | 0.00 |
| 107 | 56800.00 | 0.00 | 0.00 | 0.00 |
| 109 | 15870.00 | 0.00 | 0.00 | 0.00 |
Same grid, with 0.00 where the NULLs were. DEFAULT ON NULL (0) goes inside the PIVOT clause, straight after the IN list.
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.
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;| CUSTOMER_ID | N_SHIPPED | N_PENDING | N_CANCELLED | N_RETURNED |
|---|---|---|---|---|
| 101 | 9 | 0 | 0 | 0 |
| 102 | 4 | 0 | 0 | 2 |
| 103 | 4 | 0 | 1 | 0 |
| 104 | 3 | 0 | 1 | 0 |
| 105 | 4 | 1 | 0 | 0 |
| 106 | 2 | 1 | 0 | 0 |
| 107 | 5 | 0 | 0 | 0 |
| 109 | 3 | 0 | 0 | 0 |
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.
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.
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (SUM(AMOUNT) FOR STATUS IN (ANY ORDER BY STATUS))
ORDER BY CUSTOMER_ID;| CUSTOMER_ID | 'CANCELLED' | 'PENDING' | 'RETURNED' | 'SHIPPED' |
|---|---|---|---|---|
| 101 | NULL | NULL | NULL | 61660.00 |
| 102 | NULL | NULL | 1830.00 | 4230.50 |
| 103 | 1500.00 | NULL | NULL | 14135.25 |
| 104 | 2250.00 | NULL | NULL | 6826.25 |
| 105 | NULL | 6900.00 | NULL | 29665.00 |
| 106 | NULL | 640.00 | NULL | 3120.00 |
| 107 | NULL | NULL | NULL | 56800.00 |
| 109 | NULL | NULL | NULL | 15870.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.
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;| CUSTOMER_ID | 'CANCELLED' | 'PENDING' | 'RETURNED' | 'SHIPPED' |
|---|---|---|---|---|
| 101 | NULL | NULL | NULL | 61660.00 |
| 102 | NULL | NULL | 1830.00 | 4230.50 |
| 103 | 1500.00 | NULL | NULL | 14135.25 |
| 104 | 2250.00 | NULL | NULL | 6826.25 |
| 105 | NULL | 6900.00 | NULL | 29665.00 |
| 106 | NULL | 640.00 | NULL | 3120.00 |
| 107 | NULL | NULL | NULL | 56800.00 |
| 109 | NULL | NULL | NULL | 15870.00 |
Identical output. Pick whichever reads better to you. Neither one is more correct than the other.
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.
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.
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;| CUSTOMER_ID | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| 101 | NULL | 7460.00 | 8820.00 | 9640.00 |
| 102 | 1240.00 | NULL | 1080.00 | NULL |
| 103 | 3910.00 | 4025.00 | NULL | NULL |
| 104 | NULL | NULL | 2540.00 | NULL |
| 105 | 8340.00 | 6900.00 | NULL | NULL |
| 106 | 1690.00 | NULL | NULL | NULL |
| 107 | 11200.00 | 12850.00 | 13100.00 | NULL |
| 109 | NULL | 9940.00 | 5930.00 | NULL |
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.
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;| QTR | N_ORDERS | TOTAL |
|---|---|---|
| Q1-2024 | 5 | 26380.00 |
| Q2-2024 | 6 | 41175.00 |
| Q3-2024 | 5 | 31470.00 |
| Q4-2024 | 2 | 9640.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.
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.
SELECT *
FROM (SELECT CUSTOMER_ID, STATUS, AMOUNT FROM ORDERS)
PIVOT (AMOUNT FOR STATUS IN ('SHIPPED', 'PENDING'))
ORDER BY CUSTOMER_ID;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.
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
PIVOTturns 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.PIVOTconsumes the column named inFORand 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_IDgives you one row per source row instead of one per group. On this data that is the difference between8rows and41. - 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
INlist is dropped, not folded elsewhere, and the row count does not change. So check the list against aSELECT DISTINCTevery time. - Empty cells are whatever the aggregate returns for an empty group:
NULLforSUM,0forCOUNT.DEFAULT ON NULLoverrides the first case and is not needed for the second. IN (ANY ORDER BY ...)andIN (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 aboutFOR. Check the aggregate.
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.