skip to content

In SQL, how do you unpivot a table with one row per product and twelve month columns into one row per product-month using UNION ALL?

level: juniorimportance: should knowfreq 38%

answer

  1. the month lives in a column name
  2. one SELECT per column
  3. a literal label in each branch
  4. stack without removing duplicates
  5. source rows times twelve

basics

~20 s

Write one SELECT per month column, each returning the product key, a month label and that column under a shared alias, and stack them with UNION ALL. Twelve branches give exactly twelve output rows per source row.

solid answer

~50 s

Unpivoting turns columns into rows, and you need it because a table with `jan_sales` through `dec_sales` cannot be filtered, grouped or joined by month: the month is in a column name, not in the data. I write one `SELECT` per month column. Each branch returns `product_id`, a literal such as `1 AS month_no`, and that month's column as `amount`, and `UNION ALL` stacks the branches. Output names come from the first branch and later branches match by position, so every branch lists the same columns in the same order. I use `UNION ALL` rather than `UNION`, because `UNION` removes duplicate rows, which would quietly collapse repeated source rows and add a dedupe step. The result has exactly twelve rows per source row, NULL months included, and that gives me a count to check: source rows times twelve.

code

sql · 10 lines
sql
WITH sales_wide (product_id, jan_sales, feb_sales, mar_sales) AS (
  VALUES (1, 10, NULL, 30),
         (2, 5, 7, NULL)
)
SELECT product_id, 1 AS month_no, jan_sales AS amount FROM sales_wide
UNION ALL
SELECT product_id, 2, feb_sales FROM sales_wide
UNION ALL
SELECT product_id, 3, mar_sales FROM sales_wide
ORDER BY product_id, month_no;

go deeper

for a junior

Recall the shape: one SELECT per month column, a literal month label, the column under a shared alias, all joined with UNION ALL. Be able to write it on a whiteboard for three months.

for a middle

Explain why the month has to become data, why names come from the first branch, and how to predict the row count before running anything. Mention that NULL cells still produce rows.

for a senior

Treat the unpivot as a load step you can verify. State the expected row count, say what a mislabelled branch does to a report, and name the cost of repeating the source per branch.

for a principal

The form is rarely the decision. The useful angle is where reshaping lives: unpivot once at load so every consumer gets long rows, rather than letting each report carry its own twelve branches.

## Why a query needs unpivoting A **wide** table stores one kind of fact across many columns. A spreadsheet loaded into a warehouse is the usual source: one row per product, then `jan_sales`, `feb_sales`, and so on up to `dec_sales`. People read that layout comfortably across the page, but SQL works on rows, and here the month is part of a column name rather than a value. **Unpivoting** rewrites the table in **long** form, also called tidy form: one row per product-month, with a column saying which month and a column holding the amount. | Task | Wide table | Long table | |---|---|---| | Filter to spring | Name the three columns by hand | `WHERE month_no BETWEEN 3 AND 5` | | Total per month | Twelve separate `SUM` expressions | `GROUP BY month_no` | | Join to a calendar | No month value to join on | Join on the month column | | Add a new month | Change the table's columns | Insert more rows | ## The UNION ALL form The form works on every mainstream SQL engine, because it uses nothing more than `SELECT` and a set operator. It is shown here with three months; a full table takes twelve branches. ```sql SELECT product_id, 1 AS month_no, jan_sales AS amount FROM sales_wide UNION ALL SELECT product_id, 2, feb_sales FROM sales_wide UNION ALL SELECT product_id, 3, mar_sales FROM sales_wide ORDER BY product_id, month_no; ``` To build it: 1. Pick the **identifying columns** that every output row must carry, here `product_id`. 2. Write one `SELECT` per column you are unpivoting. 3. Add a **literal label** that says which column the value came from. 4. Give the label and the value their names in the first branch, because the output takes its column names from there. 5. Stack the branches with `UNION ALL`, keeping the columns in the same order in each one. ## Why UNION ALL and not UNION `UNION` removes duplicate rows from its result; `UNION ALL` keeps everything. An unpivot should create no duplicates of its own, because the label differs between branches, so the removal can only do harm: - If the source holds the same product twice with the same figures, `UNION` silently merges rows that were separate facts. - If someone forgets the label, `UNION` merges any two months that hold the same amount for a product, and totals fall. - Even when nothing merges, the engine still has to do the work of finding duplicates. ## What the result should look like A correct unfiltered unpivot has a row count you can state in advance: **source rows times unpivoted columns**. A hundred products and twelve months give 1,200 rows, whatever the cells contain. A NULL cell still produces a row, with a NULL `amount`, because a branch selects the column for every source row whatever it holds. Dropping those rows is a separate decision that you make with a filter. The rows arrive in no guaranteed order. A set operation does not promise that one branch's rows come before the next's, so add `ORDER BY` if the order matters. ## Mistakes that still run None of these raises an error, which is what makes them expensive: - **A mismatched label**, such as `3` paired with `feb_sales`, reports February's money as March. - **A text label** such as `'jan'` sorts alphabetically, so April comes first. A month number or a real date sorts correctly and can join to a calendar. - **A missing identifying column** gives amounts that no longer say which product they belong to. - **A branch left out** gives eleven months and a total that looks plausible. ## Where this form stops being enough Twelve branches mean twelve copies of the source and of any filter, and on most planners the table is read once per branch. A long statement is also harder to review, because a slip in one branch looks just like the correct branches around it. For a small table the extra reads barely matter. For an expensive source, `CROSS JOIN LATERAL (VALUES ...)` reads it once where the engine supports that form. Both forms need the column list written out when the query is written, and both need every unpivoted column to share a compatible type.

  • Why use a month number or a date as the label rather than text like 'jan'?
    Text sorts alphabetically, so `'apr'` comes before `'jan'` and every chart or running total needs a separate sort key. A month number or a real date sorts in calendar order, supports range filters such as `BETWEEN 3 AND 5`, and joins directly to a calendar table. The label becomes real data the moment it leaves the column name, so give it a real type.
  • Where do the output column names of a UNION ALL unpivot come from?
    From the first branch. That is why `1 AS month_no` and `jan_sales AS amount` are aliased there, while later branches can write just `2, feb_sales`. Later aliases are not used for naming, and values line up by position. So swapping two columns in one branch does not rename anything: it puts values under the wrong heading, or fails if the types are incompatible.

Think of tearing each spreadsheet row into twelve slips, each stamped with the product and the month. A blank cell still gets a slip with nothing written on it, and you only lose it if you choose to throw it away.

  • Use UNION here, because duplicates are never wanted in an unpivot.
  • The month label is optional, because row order already shows the month.
  • A UNION ALL unpivot skips NULL cells, so the row count depends on the data.
  • Every SQL engine has an UNPIVOT keyword, so hand-written branches are never needed.
  • Each branch needs its own column aliases or the UNION ALL is rejected.