SQL theory · page 9 of 10

JSON and extensions

json against jsonb, containment, GIN indexes and trigrams.

Relational tables suit data with a fixed shape. Some data varies from row to row: a burglary file lists stolen items, a windscreen file none. PostgreSQL stores such data as JSON inside a column, and can still search and index it.

json and jsonb

jsonJSONB
Stored asthe text as writtena parsed, binary form
Keepsspacing, key order and duplicate keysone value per key; order not kept
Queryingre-parsed each timefast
IndexingnoGIN indexes

Use JSONB unless you must keep the document exactly as received.

Paths and containment

  • -> returns a JSON value, ->> returns text: doc -> 'items', doc ->> 'adjuster'.
  • @> asks whether a document contains another: doc @> '{"channel": "web"}'.
  • ? asks whether an object has a key, or an array a string element.
  • JSONB_ARRAY_ELEMENTS turns an array into rows, so its elements can be filtered and summed.

GIN indexes

A B-tree sorts whole values, which does not help to find documents that contain a key. A GIN index (generalised inverted index) works like a book's index: for each key and value, the list of rows that contain it. It serves @>, ? and full-text search. Its operator class jsonb_path_ops is smaller and faster, but serves only @>.

Extensions

An extension adds types, functions and index methods to a database with CREATE EXTENSION. pg_trgm compares texts by their trigrams, the sets of three-letter sequences they contain. Similarity is the share of trigrams two texts have in common:

\text{similarity}(a, b) = \frac{|T(a) \cap T(b)|}{|T(a) \cup T(b)|}

a % b is true when the similarity is at least 0.3, the default threshold, so misspellings and missing accents still match.

SELECT doc ->> 'channel' AS channel, COUNT(*) AS files
FROM claim_documents
GROUP BY 1
ORDER BY files DESC;
->> makes a JSON value into text that can be grouped like a column. Try it in the playground
If you filter, join or total on a JSON field every day, it has earned a real column, with a type and constraints.
Practise it on Day 9

Check your understanding

Answer every question, then check.

1. What is the difference between -> and ->>?

2. Which index serves doc @> '{"channel": "web"}'?

3. How does pg_trgm judge two names similar?

An unhandled error has occurred. Reload 🗙

Reconnecting…

Your connection to Data Analytics SQL Lab dropped, probably a Wi-Fi blip. Hold on while it reconnects. Your work is kept.

The connection could not be restored. The page will reload in a few seconds.