Reading preferences
Concept

JSONB and PostgreSQL-Specific SQL

Distinguish missing JSON keys from JSON null and SQL NULL.

database, postgresql, sql, jsonb, operators, portability

Structured 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:

idgenrehas_pagespages_type
1fictiontruenumber
2historyfalseSQL NULL
3fictiontruetext 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: number

The 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.

1. What does the PostgreSQL ->> operator return?
2. How does the example detect whether the pages key exists?
3. How is a present JSON null distinguished from a missing key in the example?
4. Should PostgreSQL JSONB operators be assumed portable to every SQL database?

References and further reading