JSONB and PostgreSQL-Specific SQL
Distinguish missing JSON keys from JSON null and SQL NULL.
database, postgresql, sql, jsonb, operators, portabilityStructured data inside a column
PostgreSQL offers json and jsonb types. jsonb stores a decomposed
representation suited to many operations and indexes; unlike json, it
does not preserve original whitespace, object-key order, or duplicate keys
in the same way. JSONB is useful for flexible attributes, but it does not
replace thoughtful relational constraints.
SQL illustration
This self-contained PostgreSQL query uses fictional values:
WITH items(id, details) AS (
VALUES
(1, '{"genre":"fiction","pages":120}'::jsonb),
(2, '{"genre":"history"}'::jsonb),
(3, '{"genre":"fiction","pages":null}'::jsonb)
)
SELECT id, details ->> 'genre' AS genre,
details ? 'pages' AS has_pages,
jsonb_typeof(details -> 'pages') AS pages_type
FROM items ORDER BY id;
Prepared result — not live execution:
| id | genre | has_pages | pages_type |
|---|---|---|---|
| 1 | fiction | true | number |
| 2 | history | false | SQL NULL |
| 3 | fiction | true | text null |
->> extracts a value as text. ? checks whether a top-level key exists.
For item 2, extracting the absent key yields SQL NULL. For item 3, the
key exists and jsonb_typeof returns the text null for the JSON null.
These are different situations even though a client may display them similarly.
See the reasoning
Follow the example one step at a time
Compare a number, a missing key, and a present JSON null. This is a prepared teaching demonstration, not live code execution.
Read a number
item 1: { pages: 120 }
key exists: true
type: numberThe key exists and jsonb_typeof reports number.
Portability and constraints
PostgreSQL's ::jsonb cast and these JSONB operators are dialect-specific;
other SQL systems have different syntax and semantics. PostgreSQL also
supports standard-style CAST(value AS jsonb), but the jsonb type remains
PostgreSQL-specific. GIN indexes can accelerate supported JSONB operations
with appropriate operator classes, but not every expression uses every GIN
index. Validate shape and types at appropriate boundaries; missing keys,
JSON null, SQL NULL, and the text "null" are not interchangeable.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
