

# `UNPIVOT`

`UNPIVOT` turns columns into rows. For each source row and each listed column, it returns a row with the name of the column and its value. The source columns that are not listed are kept in each row.

You can write `UNPIVOT` in two forms. The short form, `UNPIVOT` `source` `ON` `columns` `INTO NAME` `name_column` `VALUE` `value_column`, is a query of its own that you can also use as a subquery. In the short form, you can choose the columns with a star expression, such as `COLUMNS(* EXCLUDE (region))`. The SQL standard form follows a source in the `FROM` clause: `source` `UNPIVOT (``value_column` `FOR` `name_column` `IN (...))`.

By default, rows whose value is `NULL` are left out. To keep them, use the SQL standard form and add `INCLUDE NULLS` after `UNPIVOT`.

## Syntax
<a name="athena-duckdb-statement-select-unpivot-syntax"></a>

```sql
UNPIVOT {{source}} ON {{column}}
    [, ...] INTO NAME {{name_column}} VALUE {{value_column}}
{{source}} UNPIVOT
    [ INCLUDE NULLS ] ( {{value_column}} FOR {{name_column}} IN
    ( {{column}} [ AS '{{name}}' ] [, ...] ) )
```

## Examples
<a name="athena-duckdb-statement-select-unpivot-examples"></a>

The following SQL query turns the `q1` and `q2` columns into rows. The `NULL` value of `q2` in the `west` row is left out.

```sql
SELECT region, quarter, sales
FROM (
  UNPIVOT (
      SELECT
          * FROM (VALUES
              ('east', 10, 20),
              ('west', 30, NULL)
          ) AS t(region, q1, q2)
  )
  ON q1, q2
  INTO NAME quarter VALUE sales
)
ORDER BY region, quarter
```

The query returns the following results.


| region | quarter | sales | 
| --- | --- | --- | 
| `east` | `q1` | `10` | 
| `east` | `q2` | `20` | 
| `west` | `q1` | `30` | 

The following SQL query chooses the columns to unpivot with a star expression: every column except `region`.

```sql
SELECT region, quarter, sales
FROM (
  UNPIVOT (
      SELECT
          * FROM (VALUES
              ('east', 10, 20),
              ('west', 30, 40)
          ) AS t(region, q1, q2)
  )
  ON COLUMNS(* EXCLUDE (region))
  INTO NAME quarter VALUE sales
)
ORDER BY region, quarter
```

The query returns the following results.


| region | quarter | sales | 
| --- | --- | --- | 
| `east` | `q1` | `10` | 
| `east` | `q2` | `20` | 
| `west` | `q1` | `30` | 
| `west` | `q2` | `40` | 

The following SQL query uses the SQL standard form with `INCLUDE NULLS`, so the `NULL` value is kept.

```sql
SELECT region, quarter, sales
FROM (VALUES
    ('east', 10, 20),
    ('west', 30, NULL)
) AS t(region, q1, q2)
  UNPIVOT INCLUDE NULLS (sales FOR quarter IN (q1, q2))
ORDER BY region, quarter
```

The query returns the following results.


| region | quarter | sales | 
| --- | --- | --- | 
| `east` | `q1` | `10` | 
| `east` | `q2` | `20` | 
| `west` | `q1` | `30` | 
| `west` | `q2` | `NULL` | 