Skip to main content

PostgreSQL JSONB: Tell a Missing Key from JSON null

Updated 3 min readMarkdown
Part of seriesSQL Table Filtering & Schema Inspection
PostgreSQL JSONB: Tell a Missing Key from JSON null

When a PostgreSQL JSONB field contains an explicit null, #>> produces the same SQL NULL you get from a missing path. To tell them apart, keep the extracted value as JSONB with #> and check it with jsonb_typeof().

Imagine you are reviewing a retry log. If the request object is present, an absent retry key and an explicitly null retry key tell you different things about what the producer sent. An event whose request is a string needs a separate shape check.

Show the original payload beside both extractions

This query uses synthetic records and reads only the rows defined in the query.

WITH sample(id, payload) AS (
    VALUES
        (1, '{"request":{"retry":2}}'::jsonb),
        (2, '{"request":{"retry":null}}'::jsonb),
        (3, '{"request":{}}'::jsonb),
        (4, '{"request":{"retry":"null"}}'::jsonb),
        (5, '{"request":"unavailable"}'::jsonb)
)
SELECT id,
       payload,
       payload #>> '{request,retry}' AS retry_text,
       jsonb_typeof(payload #> '{request,retry}') AS retry_json_type,
       CASE
         WHEN jsonb_typeof(payload -> 'request') IS DISTINCT FROM 'object'
           THEN 'request is missing or not an object'
         WHEN (payload #> '{request,retry}') IS NULL THEN 'missing key'
         WHEN jsonb_typeof(payload #> '{request,retry}') = 'null' THEN 'JSON null'
         ELSE 'has value'
       END AS retry_state
FROM sample
ORDER BY id;

Check these values in the result grid:

id retry_text retry_json_type retry_state
1 Text 2 Text number has value
2 SQL NULL Text null JSON null
3 SQL NULL SQL NULL missing key
4 Text null Text string has value
5 SQL NULL SQL NULL request is missing or not an object

Rows 3 and 5 look identical in the two extraction columns. The parent check keeps a malformed request out of the missing-retry count. If a SQL NULL payload needs a separate label in your audit, check payload IS NULL before the parent check.

Inspect one unexpected row in the grid

For a single complex record, find that row in its source table by its identifier. In SqlOtter, the desktop database client we build, open the selected cell’s field editor. If it offers Edit Mode → JSON Mode, switch to it and expand request to see whether retry is absent, null, or the string "null". Close with Cancel when you only need to inspect it. The editor entry depends on the build, field type, and permissions. Use the SQL query to classify rows in bulk.

PostgreSQL JSON functions and operators · SqlOtter field editor walkthrough

About the author

  • SqlOtter , The world's most powerful database management tool

No comments yet. Be the first to comment.