AI Hints
PostgreSQL · Lesson 42 of 120

JSONB Containment

Match a shape.

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

Find customers who want the newsletter and like fantasy. Containment asks, does this document contain this smaller document? It's short, and it can use an index.

  • Newsletter = true
  • Likes Fantasy
  • @>

Contains this shape

At sign greater than checks that prefs contains the JSON on the right. Arrays inside match if they include the listed items. Run it. Newsletter readers who like fantasy.

query.sqlsql
SELECT first_name, prefs
FROM customers
WHERE prefs @> '{"newsletter": true, "genres": ["Fantasy"]}'
LIMIT 3;
Output
 first_name |                             prefs
------------+----------------------------------------------------------------
 Finn       | {"genres": ["Fantasy"], "newsletter": true}
 Maya       | {"genres": ["Fantasy", "Thriller"], "newsletter": true}
 Diego      | {"format": "ebook", "genres": ["Fantasy"], "newsletter": true}
(3 rows)

Key operators

Question mark tests if a key exists. Question mark bar tests for any of several keys. Containment matches a shape. And a GIN index speeds up all of these.

OperatorMeans
doc ? 'key'key exists
doc ?| array[...]any key exists
doc @> '{...}'contains shape
GIN indexmakes them fast

Summary

Containment matches documents by shape, and works with GIN indexes. Next, changing JSONB values.

Key takeaways
  • @>
  • ?
  • GIN
Next up: Updating JSONB — change one key