AI Hints
PostgreSQL · Lesson 41 of 120

Querying JSONB

Filter by what is inside.

⏱ 2 min read▶ Video at 35:49🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Which books have more than five hundred pages? Which customers want the newsletter? We can filter on values deep inside JSONB.

  • Over 500 pages?
  • Wants newsletter?
  • Filter inside

Filter on JSON values

Double arrow gives text, so we cast pages to an integer before comparing. Run it. Long books, with their page counts.

query.sqlsql
SELECT title, (details ->> 'pages')::int AS pages
FROM books
WHERE (details ->> 'pages')::int > 500
ORDER BY pages DESC;
Output
          title           | pages
--------------------------+-------
 Wild Coast               |   588
 Empires of Salt          |   576
 The Silent Orchard       |   550
 Startup Stories          |   544
 Moonlight Express        |   544
 Crown of Ash             |   522
 A Short History of Bread |   519
 SQL in a Weekend         |   509
(8 rows)

Nested values

Prefs has a genres array inside. Hash double arrow follows a path, here the first genre. Jsonb array length counts the items. Run it. Customers, their first favourite genre, and how many they like.

query.sqlsql
SELECT first_name,
       prefs #>> '{genres,0}'          AS first_genre,
       jsonb_array_length(prefs -> 'genres') AS how_many
FROM customers
ORDER BY customer_id
LIMIT 3;
Output
 first_name | first_genre | how_many
------------+-------------+----------
 Tara       | Cooking     |        3
 Grace      | Thriller    |        1
 Finn       | Fantasy     |        1
(3 rows)

Summary

Cast JSONB text to compare numbers, and use paths to reach nested values. Next, the containment operator.

Key takeaways
  • ->> + cast
  • #>> path
  • Nested
Next up: JSONB Containment — match a shape