JSON in PostgreSQL

Draft

jsonb lets PostgreSQL store structured documents while still querying fields inside them. It is useful, but it is still data inside a table.

Extract fields

The ->> operator extracts a JSON value as text.

SELECT email, profile ->> 'plan' AS plan
FROM accounts
ORDER BY email;
emailplan
ada@example.compro
grace@example.comfree
linus@example.compro
Sort  (cost=61.98..64.11 rows=850 width=64)
  Sort Key: email
  ->  Seq Scan on accounts  (cost=0.00..20.62 rows=850 width=64)

Filter nested JSON

JSON operators can reach nested values inside a jsonb column.

SELECT email
FROM accounts
WHERE profile -> 'settings' ->> 'email' = 'true';
email
ada@example.com
Seq Scan on accounts  (cost=0.00..24.88 rows=4 width=32)
  Filter: (((profile -> 'settings'::text) ->> 'email'::text) = 'true'::text)

Containment

The @> operator asks whether jsonb contains another jsonb document.

SELECT email
FROM accounts
WHERE profile @> '{"plan": "pro"}';
email
ada@example.com
linus@example.com
Seq Scan on accounts  (cost=0.00..20.62 rows=8 width=32)
  Filter: (profile @> '{"plan": "pro"}'::jsonb)

Try Yourself

Loaded Database:json-in-postgresql.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Select emails for accounts on the pro plan.
2.Select emails for accounts whose JSON settings.email value is true.

What We Learned

  • jsonbstores JSON in a binary form PostgreSQL can query.
  • ->extracts a JSON value.
  • ->>extracts a JSON value as text.
  • @>checks whether one jsonb value contains another.