SQL Dojo
Keyword

Reading JSON in SQL: keys, null and missing

Read the fields of a JSON column as ordinary columns, cast the numbers that come out as text, and tell a key set to null from a missing key.

You need it when a column holds a JSON document (an event's payload, an API response) and you want its fields as ordinary columns.

SELECT event_id,
       payload ->> 'cart_id'                 AS cart_id,
       CAST(payload ->> 'items' AS INTEGER)  AS items,
       payload -> 'customer' ->> 'country'   AS country
FROM checkout_events;

-> returns JSON, to go one level deeper; ->> returns text. A number read with ->> is text too: cast it before you compare, sort or add, or '12' comes before '9'.

The trap. {"coupon": null} and {} say different things: the key was sent empty, or it does not exist (an older app). ->> turns both into SQL NULL, so a count of "no coupon" mixes them. Test the key with ->, which keeps the JSON null: (payload -> 'coupon') IS NULL holds only when the key is missing.

On your warehouse. Postgres and DuckDB use these arrows; on jsonb, Postgres also tests a key with payload ? 'coupon'. Snowflake reads payload:items::INTEGER and finds a JSON null with IS_NULL_VALUE(payload:coupon). BigQuery writes JSON_VALUE(payload, '$.items'), NULL in both cases; on a JSON column, JSON_TYPE(payload.coupon) = 'null' finds the JSON null. Databricks reads payload:items on a string column, NULL in both cases; on a VARIANT column, is_variant_null(payload:coupon).

WITH checkout_events(event_id, payload) AS (VALUES
  (1, CAST('{"cart_id": "c101", "items": "3", "coupon": "SPRING10"}' AS JSON)),
  (2, CAST('{"cart_id": "c102", "items": "12", "coupon": null}' AS JSON)),
  (3, CAST('{"cart_id": "c103", "items": "9"}' AS JSON)))
SELECT event_id,
       payload ->> 'coupon' AS coupon,
       CASE WHEN (payload -> 'coupon') IS NULL THEN 'missing'
            WHEN (payload ->> 'coupon') IS NULL THEN 'null'
            ELSE 'set' END AS coupon_state
FROM checkout_events
ORDER BY event_id;
event_idcouponcoupon_state
1SPRING10set
2NULLnull
3NULLmissing
Try it in Randori
WITH checkout_events(event_id, payload) AS (VALUES
  (1, CAST('{"cart_id": "c101", "items": "3"}' AS JSON)),
  (2, CAST('{"cart_id": "c102", "items": "12"}' AS JSON)),
  (3, CAST('{"cart_id": "c103", "items": "9"}' AS JSON)))
SELECT MAX(payload ->> 'items') AS most_items_as_text,
       MAX(CAST(payload ->> 'items' AS INTEGER)) AS most_items
FROM checkout_events;
most_items_as_textmost_items
912
Try it in Randori