Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 14 / Stage 3

Semi-structured data and search

Goal: Use PostgreSQL where rigid columns stop — arrays, JSONB and its whole operator family, the standard SQL/JSON functions, GIN indexing, an honest "JSONB or columns?" checklist, full-text search and fuzzy matching. Time: ~2.5 hours

What you will learn

  • Arrays: columns, ANY, unnest, operators
  • JSON vs JSONB — and why JSONB is usually right
  • Querying JSONB: ->, ->>, #>>, @>, ?
  • Building JSON from rows: jsonb_build_object, jsonb_agg, to_jsonb
  • JSON path: jsonb_path_query and friends
  • The SQL/JSON standard functions, including PostgreSQL 17's JSON_TABLE
  • Indexing JSONB with GIN
  • When to use JSONB and when to use columns
  • Full-text search: tsvector, tsquery, ranking
  • Fuzzy matching with pg_trgm

shopdb's events.payload column has been waiting since Part 1 for this lesson.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Try each one yourself first, in psql against shopdb. Then check the solution.


Exercise 1: Bundles

What to do: Create promo_bundles with an integer[] of product ids ('Work-from-home kit' = 1, 9, 10; "Reader's corner" = 5, 6, 9). Then: (a) which bundles contain product 9? (b) every bundle exploded to its product names.

Sample output (b):

       bundle       |      product       
--------------------+--------------------
 Work-from-home kit | Laptop Pro 14
 Work-from-home kit | Desk Lamp
 Work-from-home kit | USB-C Cable
 Reader's corner    | SQL for Beginners
 Reader's corner    | Postgres Deep Dive
 Reader's corner    | Desk Lamp
(6 rows)

💡 Hint: (a) 9 = ANY (product_ids); (b) unnest in a LATERAL, joined to products.


Show the solution to Exercise 1
-- Exercise 1: Bundles (re-runnable)
DROP TABLE IF EXISTS promo_bundles;
CREATE TABLE promo_bundles (
  bundle_id   integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        text NOT NULL,
  product_ids integer[] NOT NULL
);
INSERT INTO promo_bundles (name, product_ids) VALUES
  ('Work-from-home kit', ARRAY[1, 9, 10]),
  ('Reader''s corner',    ARRAY[5, 6, 9]);
-- (a) bundles containing product 9:
SELECT name FROM promo_bundles WHERE 9 = ANY (product_ids);
-- (b) exploded to product names:
SELECT b.name AS bundle, p.name AS product
FROM promo_bundles b
CROSS JOIN LATERAL unnest(b.product_ids) AS u(product_id)
JOIN products p ON p.product_id = u.product_id
ORDER BY b.bundle_id, p.product_id;

Exercise 2: Mobile moments

What to do: Every event that happened on a mobile device, with the customer's name — filtered the GIN-friendly way.

Sample output:

 event_id | first_name | event_type 
----------+------------+------------
        1 | Asha       | view
        2 | Asha       | cart
        6 | Vikram     | view
        7 | Vikram     | cart
(4 rows)

💡 Hint: payload @> '{"device": "mobile"}' — containment, not ->> equality.


Show the solution to Exercise 2
-- Exercise 2: Mobile moments
SELECT e.event_id, c.first_name, e.event_type
FROM events e
JOIN customers c ON c.customer_id = e.customer_id
WHERE e.payload @> '{"device": "mobile"}'
ORDER BY e.event_id;

Exercise 3: The API shape

What to do: For customer 3, one jsonb value an API could return verbatim: the name plus an ordered array of her orders (id, date, status).

Sample output:

 {"orders": [{"date": "2025-02-20", "status": "shipped", "order_id": 4}, {"date": "2025-04-12", "status": "delivered", "order_id": 8}], "customer": "Meera"}
(1 row)

💡 Hint: jsonb_build_object outside, jsonb_agg(jsonb_build_object(...) ORDER BY ...) inside. (jsonb doesn't keep your key order — that's the type working as designed.)


Show the solution to Exercise 3
-- Exercise 3: The API shape
SELECT jsonb_build_object(
         'customer', c.first_name,
         'orders', jsonb_agg(
           jsonb_build_object('order_id', o.order_id,
                              'date', o.order_date,
                              'status', o.status)
           ORDER BY o.order_id)
       ) AS response
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id = 3
GROUP BY c.first_name;

Exercise 4: Flatten the payloads

What to do: With JSON_TABLE, turn every event payload into typed columns — device, product_id, order_id — one relational row per event, NULLs where a field is absent.

Sample output:

 event_id | event_type | device  | product_id | order_id 
----------+------------+---------+------------+----------
        1 | view       | mobile  |          1 |         
        2 | cart       | mobile  |          1 |         
        3 | purchase   | desktop |            |        1
        4 | view       | desktop |          3 |         
        5 | purchase   | desktop |            |        2
        6 | view       | mobile  |          2 |         
        7 | cart       | mobile  |          2 |         
(7 rows)

💡 Hint: JSON_TABLE(e.payload, '$' COLUMNS (device text PATH '$.device', ...)) in the FROM.


Show the solution to Exercise 4
-- Exercise 4: Flatten the payloads (JSON_TABLE, PostgreSQL 17)
SELECT e.event_id, e.event_type, jt.device, jt.product_id, jt.order_id
FROM events e,
     JSON_TABLE(e.payload, '$'
       COLUMNS (
         device     text    PATH '$.device',
         product_id integer PATH '$.product_id',
         order_id   integer PATH '$.order_id'
       )
     ) AS jt
ORDER BY e.event_id;

Exercise 5: Catalogue search

What to do: Full-text search product names for "postgres OR sql", ranked — using the parser made for human input.

Sample output:

        name        |    rank     
--------------------+-------------
 Postgres Deep Dive | 0.030396355
 SQL for Beginners  | 0.030396355
(2 rows)

💡 Hint: websearch_to_tsquery('english', 'postgres OR sql') and @@, ranked with ts_rank.


Show the solution to Exercise 5
-- Exercise 5: Catalogue search
SELECT name,
       ts_rank(to_tsvector('english', name), query) AS rank
FROM products,
     websearch_to_tsquery('english', 'postgres OR sql') AS query
WHERE to_tsvector('english', name) @@ query
ORDER BY rank DESC, name;

Exercise 6: The typo-proof finder

What to do: A customer typed coffe. Find what they meant, with the per-word similarity score.

Sample output:

     name     | best_word 
--------------+-----------
 Coffee Maker | 0.8333333
(1 row)

💡 Hint: word_similarity('coffe', name) > 0.3 — the word form, since product names are multi-word.

Show the solution to Exercise 6
-- Exercise 6: The typo-proof finder
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT name, word_similarity('coffe', name) AS best_word
FROM products
WHERE word_similarity('coffe', name) > 0.3
ORDER BY best_word DESC;

Common mistakes

Mistake What happens Fix
Core fields buried in jsonb No constraints, no joins, casts everywhere Columns for the backbone; jsonb for the honest leftovers
-> where ->> was meant jsonb compared with text, confusing errors -> to navigate, ->> to extract
Filtering with ->> and expecting the GIN index to help Sequential scans anyway @> containment, or an expression index
json when jsonb would do Re-parsing on every query, no operators/indexes jsonb unless byte-exact text is a requirement
Arrays as relationships No FK integrity, painful reverse queries Junction tables for real relationships
LIKE '%term%' as "search" No stemming, no ranking, no typo tolerance Full-text (meaning) + pg_trgm (typos)

Quick recap

  • Arrays hold atomic lists you query with ANY and unnest; relationships still belong to junction tables.
  • jsonb stores parsed meaning (pick it); json stores exact text (rarely needed).
  • Navigate with ->, extract text with ->>, and filter with @> and ? — the shapes a GIN index can serve.
  • Build API JSON inside the database with jsonb_build_object and jsonb_agg, and unpack documents with JSON_TABLE (new in PG17).
  • Give known, queried, constrained fields real columns; keep varying, third-party, sparse data in jsonb.
  • Full-text search is tsvector @@ tsquery with ranking, pg_trgm handles typos and %middle% patterns, and both ride on generated columns with GIN indexes underneath.

Checklist

Before the Stage 3 project, make sure you can:

  • Explode an array against a lookup table with unnest + LATERAL.
  • State the json/jsonb difference and pick in one breath.
  • Filter events by containment and explain why @> beats ->> for indexes.
  • Shape a customer-with-orders JSON response in one query.
  • Flatten a payload with JSON_TABLE into typed columns.
  • Sketch the full search stack: tsvector column, tsquery match, trigram fallback.

Read more: the official JSON types and JSON functions chapters, full-text search introduction, and pg_trgm.

Search the guide