# BigQuery PIVOT: Syntax and Examples | Masthead

PIVOT turns row values into columns with an aggregate: PIVOT(SUM(revenue) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4')) gives one revenue column per quarter. The IN list must be constants, so build it with EXECUTE IMMEDIATE when the values are dynamic.

> For the index of this section of the site, see [llms.txt](https://mastheadata.com/llms.txt)

BigQuery · Query syntax

# BigQuery PIVOT

PIVOT turns row values into columns with an aggregate: PIVOT(SUM(revenue) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4')) gives one revenue column per quarter. The IN list must be constants, so build it with EXECUTE IMMEDIATE when the values are dynamic.

GoogleSQL for BigQuery · Checked against the [official reference](https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#pivot_operator) in November 2026

`PIVOT` is an operator in the `FROM` clause. For each value in the `IN` list it creates one output column, holding the aggregate of the rows whose `FOR` column equals that value. Every other column of the input that is not aggregated and not the `FOR` column becomes an implicit grouping column. That is the part that surprises people: if the input still has an `order_id` or a timestamp, you get one row per order instead of one per customer. Select only the grouping columns, the pivot column and the measure in a subquery before pivoting.

Column names come from the values: a string becomes the column name as is, a number `1` becomes `_1`, a date becomes `_2026_11_01`. Values that are not valid identifiers, or types other than strings, numbers, BOOL, DATE and STRUCT, need an alias: `IN ('Q1' AS q1, 'Q2' AS q2)`. With several aggregates, each needs an alias that is used as a prefix: `SUM(units) AS units, COUNT(*) AS orders` produces `units_Q1`, `orders_Q1` and so on. A value with no matching rows produces NULL, not 0; wrap the columns in `IFNULL` or `COALESCE` in the outer SELECT if you need zeros.

The aggregate must ignore NULL inputs (`COUNT(*)` is also allowed, and `ARRAY_AGG` only with `IGNORE NULLS`), and the `IN` values must be literals: no subqueries, query parameters or script variables. For a column list that changes, generate the SQL string with `STRING_AGG` and run it with [EXECUTE IMMEDIATE](https://mastheadata.com/bigquery/sql/execute-immediate.md). The reverse operation is [UNPIVOT](https://mastheadata.com/bigquery/sql/unpivot.md). PIVOT is also written as a `SUM(IF(quarter = 'Q1', revenue, NULL))` per column, which is how you would do it in PostgreSQL or MySQL.

## Syntax

```
SELECT ...
FROM from_item
PIVOT (
  aggregate_function(expression) [[AS] prefix][, ...]
  FOR input_column IN (value [[AS] alias][, ...])
) [[AS] table_alias]
```

## Arguments and return value

| Argument | Description |
| --- | --- |
| `aggregate_function` | An aggregate that ignores NULL inputs, such as SUM, MAX, MIN, AVG, ANY\_VALUE, STRING\_AGG or COUNT (COUNT(\*) is allowed too); ARRAY\_AGG needs IGNORE NULLS. Give each aggregate a prefix alias when there are several. |
| `input_column` | The column whose values become new columns. Must be groupable. |
| `value` | A constant to match against `input_column`. Each value produces one column; an optional alias names it. |
| `from_item` | A table or subquery. All its columns other than the aggregated expression and `input_column` become grouping columns. |

**Returns:** One row per combination of the remaining (grouping) columns, with one column per IN value and aggregate.

## Examples

### Revenue per region and quarter

```
WITH sales AS (
  SELECT 'EMEA' AS region, 'Q1' AS quarter, 120 AS revenue UNION ALL
  SELECT 'EMEA', 'Q2', 80 UNION ALL
  SELECT 'EMEA', 'Q2', 40 UNION ALL
  SELECT 'AMER', 'Q1', 200 UNION ALL
  SELECT 'AMER', 'Q3', 90
)
SELECT *
FROM sales
PIVOT (SUM(revenue) FOR quarter IN ('Q1', 'Q2', 'Q3'))
ORDER BY region;
```

Result
| region | Q1 | Q2 | Q3 |
| --- | --- | --- | --- |
| AMER | 200 | NULL | 90 |
| EMEA | 120 | 120 | NULL |

### An extra column silently becomes a grouping column

`order_id` is still in the input, so PIVOT groups by it and returns one row per order. Selecting only `region`, `quarter` and `revenue` in a subquery fixes it.

```
WITH sales AS (
  SELECT 'o1' AS order_id, 'EMEA' AS region, 'Q1' AS quarter, 120 AS revenue UNION ALL
  SELECT 'o2', 'EMEA', 'Q2', 80
)
SELECT *
FROM sales
PIVOT (SUM(revenue) FOR quarter IN ('Q1', 'Q2'))
ORDER BY order_id;
```

Result
| order\_id | region | Q1 | Q2 |
| --- | --- | --- | --- |
| o1 | EMEA | 120 | NULL |
| o2 | EMEA | NULL | 80 |

### Several aggregates with prefixes and column aliases

```
WITH sales AS (
  SELECT 'EMEA' AS region, 'Q1' AS quarter, 120 AS revenue UNION ALL
  SELECT 'EMEA', 'Q1', 30 UNION ALL
  SELECT 'EMEA', 'Q2', 80
)
SELECT *
FROM sales
PIVOT (
  SUM(revenue) AS revenue,
  COUNT(*) AS orders
  FOR quarter IN ('Q1' AS q1, 'Q2' AS q2)
);
```

Result
| region | revenue\_q1 | orders\_q1 | revenue\_q2 | orders\_q2 |
| --- | --- | --- | --- | --- |
| EMEA | 150 | 2 | 80 | 1 |

### Dynamic pivot columns with EXECUTE IMMEDIATE

Builds the IN list from the data, then runs the generated query. The lookup query is billed like any other.

```
DECLARE quarters STRING;
SET quarters = (
  SELECT STRING_AGG(DISTINCT FORMAT("'%s'", quarter), ', ' ORDER BY FORMAT("'%s'", quarter))
  FROM `project.dataset.sales`
);
EXECUTE IMMEDIATE FORMAT("""
  SELECT * FROM (SELECT region, quarter, revenue FROM `project.dataset.sales`)
  PIVOT (SUM(revenue) FOR quarter IN (%s))
""", quarters);
```

## Common mistakes

*   Leaving extra columns in the input. Every column that is not aggregated or pivoted becomes a grouping column, so rows don't collapse. Pivot a subquery that selects only what you need.
*   Expecting 0 for missing combinations. Values with no rows give NULL; use `IFNULL(Q1, 0)` in the outer query.
*   Passing the IN list as a subquery or variable. PIVOT needs constants; generate the statement with EXECUTE IMMEDIATE instead.
*   Pivoting with `ARRAY_AGG(x)`. Aggregates that keep NULLs are rejected with "Use of aggregate function ARRAY\_AGG as PIVOT expression is not supported unless IGNORE NULLS is specified"; write `ARRAY_AGG(x IGNORE NULLS)`.

## Cost and performance

*   PIVOT is an aggregation, so cost is the scan of its input: filter and project columns in the subquery before the PIVOT, and only those columns are read.

## FAQ

How do I pivot rows to columns in BigQuery?

`SELECT * FROM (SELECT key, category, value FROM t) PIVOT (SUM(value) FOR category IN ('a', 'b', 'c'))`. Each IN value becomes a column.

How do I pivot with a dynamic list of columns?

BigQuery requires constants in the IN list. Build the list with `STRING_AGG` into a variable and run the query with `EXECUTE IMMEDIATE FORMAT(...)`, as in the last example.

Why are my pivoted values NULL instead of 0?

No input rows matched that value for the group, and aggregates over no rows return NULL. Replace them with `IFNULL(column, 0)` in the outer SELECT.

## Related

[UNPIVOT](https://mastheadata.com/bigquery/sql/unpivot.md)[EXECUTE IMMEDIATE](https://mastheadata.com/bigquery/sql/execute-immediate.md)[GROUP BY ROLLUP, CUBE and GROUPING SETS](https://mastheadata.com/bigquery/sql/group-by-rollup.md)[WITH (CTE)](https://mastheadata.com/bigquery/sql/with.md)[SUM](https://mastheadata.com/bigquery/functions/sum.md)[IF](https://mastheadata.com/bigquery/functions/if.md)[STRING\AGG](https://mastheadata.com/bigquery/functions/string-agg.md)

### Errors you may hit

[Syntax error: Unexpected keyword](https://mastheadata.com/bigquery/errors/syntax-error-unexpected-keyword.md)[No matching signature for function](https://mastheadata.com/bigquery/errors/no-matching-signature-for-function.md)

### More query syntax

[JOIN](https://mastheadata.com/bigquery/sql/join.md)[QUALIFY](https://mastheadata.com/bigquery/sql/qualify.md)[SELECT \ EXCEPT](https://mastheadata.com/bigquery/sql/select-except.md)[SELECT \ REPLACE](https://mastheadata.com/bigquery/sql/select-replace.md)[TABLESAMPLE SYSTEM](https://mastheadata.com/bigquery/sql/tablesample.md)[UNION ALL and UNION DISTINCT](https://mastheadata.com/bigquery/sql/union.md)[WITH RECURSIVE](https://mastheadata.com/bigquery/sql/with-recursive.md)

[All BigQuery query syntax](https://mastheadata.com/bigquery/query-syntax.md) · [All statements and clauses](https://mastheadata.com/bigquery/sql.md) · [BigQuery error messages](https://mastheadata.com/bigquery/errors.md)
---

## Other pages in sql

> For the full index of this section, see [BigQuery Reference](https://mastheadata.com/llms/llms-bigquery-reference.txt).

- [BigQuery ALTER TABLE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/alter-table.md): ALTER TABLE changes a BigQuery table without rewriting it: ADD COLUMN, DROP COLUMN, RENAME TO, RENAME COLUMN, SET OPTIONS (expiration, description, labels, partition filter) and ALTER COLUMN SET DATA TYPE for widening changes such as INT64 to NUMERIC. These are metadata changes and process no bytes.
- [BigQuery CLUSTER BY: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/cluster-by.md): CLUSTER BY sorts a BigQuery table's storage blocks by up to four columns, so queries that filter on those columns skip blocks and bill fewer bytes. Use it on large tables filtered by columns such as customer_id or status, usually on top of date partitioning.
- [BigQuery CREATE FUNCTION: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/create-function.md): CREATE FUNCTION defines a user-defined function (UDF) in SQL or JavaScript. CREATE TEMP FUNCTION lives for one query or script; CREATE FUNCTION dataset.name is persistent and shared. Prefer SQL UDFs: they are inlined, while JavaScript UDFs use more slots and lack 64-bit integers.
- [BigQuery CREATE MATERIALIZED VIEW: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/create-materialized-view.md): CREATE MATERIALIZED VIEW stores the result of an aggregation over a BigQuery table and keeps it current automatically. Queries read the small precomputed result plus recent changes instead of rescanning the base table, cutting cost for dashboards that repeat the same GROUP BY.
- [BigQuery CREATE TABLE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/create-table.md): CREATE TABLE creates a BigQuery table from a column list, from a query (CREATE TABLE AS SELECT), or both, with optional partitioning, clustering and OPTIONS such as expiration and description. Add OR REPLACE to overwrite a table or IF NOT EXISTS to skip one that exists.
- [BigQuery CREATE TEMP TABLE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/create-temp-table.md): CREATE TEMP TABLE stores intermediate results in a table that exists only for the current multi-statement query or session, without a dataset. Use it to compute an expensive step once and reuse it, instead of a CTE that BigQuery re-runs at every reference.
- [BigQuery CREATE VIEW: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/create-view.md): CREATE VIEW saves a query under a table-like name. A BigQuery view stores no data and re-runs its query on every use, billed for the underlying tables' bytes. Authorize the view on the source dataset to share a filtered subset without granting access to the tables.
- [BigQuery DECLARE and SET: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/declare-set.md): DECLARE creates a variable in a BigQuery multi-statement query and SET assigns it: DECLARE run_date DATE DEFAULT CURRENT_DATE(); SET run_date = '2026-11-22'. Variables make scripts reusable, and a date variable in a WHERE clause still prunes partitions.
- [BigQuery DELETE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/delete.md): DELETE removes the rows of a BigQuery table that match a WHERE clause, which is mandatory. A DELETE that covers whole partitions and filters only on the partitioning column can drop them without scanning bytes; any other DELETE bills the bytes read plus the size of the table or partitions it rewrites.
- [BigQuery EXECUTE IMMEDIATE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/execute-immediate.md): EXECUTE IMMEDIATE runs a SQL statement built as a string at run time, with values bound through USING and results stored with INTO. Use it for dynamic table names, generated PIVOT column lists and maintenance across many tables; bind values as parameters, never by concatenation.
- [BigQuery EXPORT DATA: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/export-data.md): EXPORT DATA writes the result of a query to files in Cloud Storage (CSV, JSON, Avro or Parquet), or to Bigtable, Spanner, Pub/Sub or AlloyDB. The export itself is free; you pay for the query that produces the data, and the URI must contain one  wildcard.
- [BigQuery GROUP BY ROLLUP, CUBE and GROUPING SETS: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/group-by-rollup.md): ROLLUP, CUBE and GROUPING SETS compute several GROUP BY levels in one query: ROLLUP(a, b) adds subtotals per a and a grand total, CUBE(a, b) adds every combination, and GROUPING SETS lists the exact groupings you want. GROUPING() tells subtotal rows from real NULLs.
- [BigQuery INFORMATION_SCHEMA.JOBS: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/information-schema-jobs.md): INFORMATION_SCHEMA.JOBS lists every BigQuery job in a project for the last 180 days, with bytes billed, slot milliseconds, errors and query text. Query it to find the most expensive queries, attribute cost by user or label, and turn total_bytes_billed into an on-demand cost estimate.
- [BigQuery INFORMATION_SCHEMA: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/information-schema.md): INFORMATION_SCHEMA is BigQuery's set of read-only metadata views for tables, columns, partitions, storage and jobs. Query mydataset.INFORMATION_SCHEMA.TABLES or region-us.INFORMATION_SCHEMA.TABLE_STORAGE to audit schemas, find large tables and estimate storage cost. Each on-demand query bills at least 10 MB.
- [BigQuery INSERT: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/insert.md): INSERT adds rows to a BigQuery table from a VALUES list or a SELECT query. On-demand it bills only the bytes the SELECT reads. Insert in batches: BigQuery is not built for row-by-row INSERTs, and after 1,500 INSERT statements on a table in a day, extra ones are queued.
- [BigQuery JOIN: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/join.md): JOIN combines rows of two tables on a condition: INNER JOIN keeps matches, LEFT, RIGHT and FULL OUTER JOIN also keep unmatched rows with NULLs, and CROSS JOIN pairs every row with every row. In BigQuery a comma or CROSS JOIN with UNNEST flattens an array column.
- [BigQuery LOAD DATA: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/load-data.md): LOAD DATA loads files from Cloud Storage (CSV, JSON, Avro, Parquet, ORC) into a BigQuery table from SQL: LOAD DATA INTO appends, LOAD DATA OVERWRITE replaces, and a missing table is created. If the load fails, the table is left unchanged.
- [BigQuery LOOP, WHILE and FOR...IN: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/loops.md): BigQuery scripts loop with LOOP ... END LOOP (exit with BREAK or LEAVE), WHILE condition DO ... END WHILE, REPEAT ... UNTIL ... END REPEAT, and FOR row IN (query) DO ... END FOR. Use them for backfills and maintenance, not row-by-row processing: each statement inside runs as its own job.
- [BigQuery MERGE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/merge.md): MERGE updates, inserts and deletes rows of a BigQuery table in one atomic statement, by matching it against a source table or query. It is BigQuery's upsert: WHEN MATCHED THEN UPDATE, WHEN NOT MATCHED THEN INSERT, and WHEN NOT MATCHED BY SOURCE THEN DELETE for rows that disappeared.
- [BigQuery PARTITION BY (partitioned tables): Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/partition-by.md): PARTITION BY in CREATE TABLE splits a BigQuery table into partitions by a DATE, TIMESTAMP or DATETIME column, by ingestion time, or by integer ranges. Queries that filter on the partitioning column read and bill only the matching partitions, which makes it the main lever on query cost.
- [BigQuery QUALIFY: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/qualify.md): QUALIFY filters rows on the result of a window function, the way HAVING filters on aggregates. Use it to keep the latest row per key or the top N per group without a subquery: QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC) = 1.
- [BigQuery SELECT * EXCEPT: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/select-except.md): SELECT  EXCEPT (col1, col2) returns every column except the ones you list. In BigQuery it also lowers on-demand cost, because excluded columns are not read: dropping a wide payload or blob column from SELECT  can cut the bytes billed by most of the table.
- [BigQuery SELECT * REPLACE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/select-replace.md): SELECT  REPLACE (expression AS column) returns every column but swaps the value of the named columns for an expression, keeping their names and positions. Use it to mask, round, cast or clean a few columns without listing all the others.
- [BigQuery TABLESAMPLE SYSTEM: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/tablesample.md): TABLESAMPLE SYSTEM (n PERCENT) reads a random subset of a BigQuery table's storage blocks instead of the whole table, so exploratory queries on large tables scan and bill only about n percent of the bytes. Results are approximate and change on every run.
- [BigQuery TRUNCATE TABLE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/truncate-table.md): TRUNCATE TABLE removes every row from a BigQuery table but keeps its schema, partitioning, clustering, description and labels. It is a metadata operation, so it costs nothing, unlike DELETE WHERE TRUE, which is billed as DML.
- [BigQuery UNION ALL and UNION DISTINCT: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/union.md): UNION ALL stacks the rows of two queries; UNION DISTINCT does the same and removes duplicates. BigQuery requires the ALL or DISTINCT keyword, matches columns by position unless you add BY NAME, and also offers INTERSECT DISTINCT and EXCEPT DISTINCT.
- [BigQuery UNPIVOT: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/unpivot.md): UNPIVOT turns columns into rows: UNPIVOT(amount FOR month IN (jan, feb, mar)) gives one row per month with its value in amount. Rows whose value is NULL are dropped unless you add INCLUDE NULLS.
- [BigQuery UPDATE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/update.md): UPDATE changes column values in existing BigQuery rows. The WHERE clause is mandatory (use WHERE TRUE to update every row), and UPDATE ... FROM joins another table. On-demand it bills the bytes read plus the full size of the table, or of the partitions being updated.
- [BigQuery WITH RECURSIVE: Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/with-recursive.md): WITH RECURSIVE defines a CTE that references itself, so a query can walk hierarchies and graphs of unknown depth: org charts, category trees, dependency lineage. BigQuery stops a recursive CTE with an error after 500 iterations.
- [BigQuery WITH (CTE): Syntax and Examples | Masthead](https://mastheadata.com/bigquery/sql/with.md): WITH defines named subqueries (common table expressions) that the rest of a query can reference like tables. In BigQuery a non-recursive CTE is not materialized: each reference runs it again, so a CTE over a large table used three times is scanned and billed three times.
- [BigQuery SQL Syntax: Statements, Clauses, DDL and DML | Masthead](https://mastheadata.com/bigquery/sql.md): BigQuery SQL syntax reference: QUALIFY, PIVOT, MERGE, CTEs, partitioned and clustered tables, scripting and INFORMATION_SCHEMA. 31 statements and clauses with examples and cost notes.
