> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# What is the ClickHouse equivalent of the Snowflake FLATTEN function for JSON?

> How to turn the keys of a JSON object or the elements of a JSON array into rows in ClickHouse, the way LATERAL FLATTEN does in Snowflake, with ARRAY JOIN and JSON functions.

In ClickHouse, you expand a JSON value into rows by extracting an array from it with a JSON function and unfolding that array with the [`ARRAY JOIN`](https://clickhouse.com/docs/reference/statements/select/array-join) clause or the [`arrayJoin`](https://clickhouse.com/docs/reference/functions/regular-functions/array-join) function. The equivalent of `FLATTEN(input => PARSE_JSON(payload))` in Snowflake is `arrayJoin(JSONExtractKeysAndValuesRaw(payload))` when `payload` is a JSON object, and `arrayJoin(JSONExtractArrayRaw(payload))` when it is a JSON array.

## Flatten the keys of an object

Create a table with JSON documents stored in a `String` column:

```sql theme={null}
CREATE TABLE events
(
    id UInt32,
    payload String
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO events VALUES
    (1, '{"a":1, "b":[77,88], "c": {"d":"X"}}'),
    (2, '{"a":2, "e":"text"}');
```

In Snowflake, a query like `SELECT t.id, f.key, f.value FROM events t, LATERAL FLATTEN(input => PARSE_JSON(t.payload)) f` returns one row for every top-level key. In ClickHouse, [`JSONExtractKeysAndValuesRaw`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONExtractKeysAndValuesRaw) returns the keys and values of an object as an `Array(Tuple(String, String))`, and `ARRAY JOIN` produces one row for every element of that array:

```sql theme={null}
SELECT
    id,
    kv.1 AS key,
    kv.2 AS value
FROM events
ARRAY JOIN JSONExtractKeysAndValuesRaw(payload) AS kv
ORDER BY id, key;
```

```text theme={null}
   ┌─id─┬─key─┬─value─────┐
1. │  1 │ a   │ 1         │
2. │  1 │ b   │ [77,88]   │
3. │  1 │ c   │ {"d":"X"} │
4. │  2 │ a   │ 2         │
5. │  2 │ e   │ "text"    │
   └────┴─────┴───────────┘
```

The values are unparsed JSON text, so strings keep their double quotes. Pass a value to a function such as `JSONExtractString` or `JSONExtractInt` to convert it, or use `JSONExtractKeysAndValues(payload, 'String')` to get all values converted to one type.

The same result is available without the `ARRAY JOIN` clause: `SELECT id, arrayJoin(JSONExtractKeysAndValuesRaw(payload)) AS kv FROM events` returns each key and value as one tuple.

To flatten a nested object instead of the top level (the `PATH` argument of `FLATTEN`), add the keys that lead to it as extra arguments, for example `JSONExtractKeysAndValuesRaw(payload, 'c')`.

## Flatten the elements of an array

For a JSON array, use [`JSONExtractArrayRaw`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONExtractArrayRaw). Join `arrayEnumerate` of the same array to get the position of each element:

```sql theme={null}
WITH JSONExtractArrayRaw(payload, 'b') AS arr
SELECT
    id,
    idx,
    value
FROM events
ARRAY JOIN
    arr AS value,
    arrayEnumerate(arr) AS idx
ORDER BY id, idx;
```

```text theme={null}
   ┌─id─┬─idx─┬─value─┐
1. │  1 │   1 │ 77    │
2. │  1 │   2 │ 88    │
   └────┴─────┴───────┘
```

Here the array is the value of the key `b`. When the document itself is an array, omit the key: `JSONExtractArrayRaw('[77,88]')` returns `['77','88']`.

`arrayEnumerate` numbers the elements from 1, while the `INDEX` column of `FLATTEN` starts at 0.

The row with `id = 2` has no key `b`, so its array is empty and `ARRAY JOIN` returns nothing for it. To keep such rows, as `OUTER => TRUE` does in Snowflake, write `LEFT ARRAY JOIN` instead of `ARRAY JOIN`. The row is then returned once, with default values (an empty string and `0` here) in the unfolded columns.

## Flatten nested objects and arrays recursively

The functions above expand one level. To walk the whole document, as `RECURSIVE => TRUE` does, use [`JSONExtractLeafPathsAndValues`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONExtractLeafPathsAndValues), which is available from ClickHouse 26.11:

```sql theme={null}
SELECT
    id,
    leaf.path AS path,
    leaf.value AS value
FROM events
ARRAY JOIN JSONExtractLeafPathsAndValues(payload) AS leaf
ORDER BY id, path;
```

```text theme={null}
   ┌─id─┬─path─┬─value─┐
1. │  1 │ a    │ 1     │
2. │  1 │ b[0] │ 77    │
3. │  1 │ b[1] │ 88    │
4. │  1 │ c.d  │ X     │
5. │  2 │ a    │ 2     │
6. │  2 │ e    │ text  │
   └────┴──────┴───────┘
```

The function returns only scalar leaves (strings, numbers and booleans), with strings unescaped. Unlike a recursive `FLATTEN`, it has no rows for the intermediate objects and arrays, and it skips `null` values.

## Flatten a column of the JSON data type

If the documents are stored in a column of the [`JSON`](https://clickhouse.com/docs/reference/data-types/newjson) data type, the paths are already parsed. [`JSONAllPaths`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONAllPaths) returns the paths of each row, and [`JSONAllValues`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONAllValues) (available from ClickHouse 26.4) returns the values as strings. Both arrays are ordered by path, so you can unfold them together:

```sql theme={null}
CREATE TABLE events_json
(
    id UInt32,
    payload JSON
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO events_json SELECT id, payload FROM events;

SELECT
    id,
    path,
    value
FROM events_json
ARRAY JOIN
    JSONAllPaths(payload) AS path,
    JSONAllValues(payload) AS value
ORDER BY id, path;
```

```text theme={null}
   ┌─id─┬─path─┬─value───┐
1. │  1 │ a    │ 1       │
2. │  1 │ b    │ [77,88] │
3. │  1 │ c.d  │ X       │
4. │  2 │ a    │ 2       │
5. │  2 │ e    │ text    │
   └────┴──────┴─────────┘
```

Nested objects are flattened into dotted paths, and an array of scalars stays one value. To get the data type of each path instead of its value, use [`JSONAllPathsWithTypes`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONAllPathsWithTypes). When you know which paths you need, read them directly as subcolumns (`payload.a`, `payload.c.d`) instead of flattening the document.

## Differences from FLATTEN

`FLATTEN` is a table function with a fixed set of output columns (`SEQ`, `KEY`, `PATH`, `INDEX`, `VALUE`, `THIS`). ClickHouse has no single function with that output. You choose the JSON function that returns the array you need and select the columns yourself:

| `FLATTEN` feature | ClickHouse |
| - | - |
| `KEY` and `VALUE` of an object | `JSONExtractKeysAndValuesRaw` |
| `INDEX` and `VALUE` of an array | `JSONExtractArrayRaw` with `arrayEnumerate` |
| `PATH => ...` | Extra key or index arguments of the JSON function |
| `OUTER => TRUE` | `LEFT ARRAY JOIN` |
| `RECURSIVE => TRUE` | `JSONExtractLeafPathsAndValues` (leaves only) |
| `SEQ`, `THIS` | The columns of the source row, which stay available next to the unfolded values |

`FLATTEN` expands an object or an array, whichever it receives. The ClickHouse functions do not: `JSONExtractKeysAndValuesRaw` returns an empty array for a JSON array, and `JSONExtractArrayRaw` returns an empty array for a JSON object, so a document of the other shape produces no rows and no error. If a column contains both shapes, tell them apart with [`JSONType`](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions#JSONType), which returns `Object` or `Array`, and unfold each shape with its own function.

## Related pages

* [Snowflake SQL translation reference](https://clickhouse.com/docs/get-started/migrate/snowflake/sql-translation-reference.md)
* [`ARRAY JOIN` clause](https://clickhouse.com/docs/reference/statements/select/array-join)
* [JSON functions](https://clickhouse.com/docs/reference/functions/regular-functions/json-functions.md)
* [`JSON` data type](https://clickhouse.com/docs/reference/data-types/newjson)
