JSON in SQL auslesen: Schlüssel, null und fehlende Schlüssel
Du brauchst das, wenn eine Spalte ein JSON-Dokument enthält (den Payload eines Ereignisses, die Antwort einer API) und du dessen Felder als normale Spalten haben möchtest.
SELECT event_id,
payload ->> 'cart_id' AS cart_id,
CAST(payload ->> 'items' AS INTEGER) AS items,
payload -> 'customer' ->> 'country' AS country
FROM checkout_events;
-> liefert JSON, um eine Ebene tiefer zu gehen; ->> liefert Text. Auch eine mit ->> gelesene Zahl ist Text:
Wandle sie um, bevor du vergleichst, sortierst oder addierst, sonst steht '12' vor '9'.
Die Falle. {"coupon": null} und {} bedeuten Verschiedenes: Der Schlüssel wurde leer übermittelt, oder es gibt
ihn gar nicht (eine ältere App-Version). ->> macht aus beidem SQL-NULL, und eine Zählung „ohne Gutschein“ wirft beides
zusammen. Prüfe den Schlüssel mit ->, das das JSON-null erhält: (payload -> 'coupon') IS NULL ist nur wahr,
wenn der Schlüssel fehlt.
In deinem Data Warehouse. Postgres und DuckDB verwenden diese Pfeile; bei jsonb prüft Postgres einen Schlüssel auch
mit payload ? 'coupon'. Snowflake liest payload:items::INTEGER und erkennt ein JSON-null mit
IS_NULL_VALUE(payload:coupon). BigQuery schreibt JSON_VALUE(payload, '$.items'), in beiden Fällen NULL; bei einer
JSON-Spalte erkennt JSON_TYPE(payload.coupon) = 'null' das JSON-null. Databricks liest payload:items bei einer
String-Spalte, in beiden Fällen NULL; bei einer VARIANT-Spalte hilft 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_id | coupon | coupon_state |
|---|---|---|
| 1 | SPRING10 | set |
| 2 | NULL | null |
| 3 | NULL | missing |
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_text | most_items |
|---|---|
| 9 | 12 |