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;
Loading plan...

Filter nested JSON

JSON operators can reach nested values inside a jsonb column.

SELECT email
FROM accounts
WHERE profile -> 'settings' ->> 'email' = 'true';
Loading plan...

Containment

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

SELECT email
FROM accounts
WHERE profile @> '{"plan": "pro"}';
Loading plan...

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.