Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PG
PostgreSQL
0/11 completed
Beginner
Why PostgreSQL?psql and your first tablesData types that matter
Intermediate
Constraints and relationshipsPostgres-powered SQLJSONB, arrays and full-text search
Advanced
Views, functions and triggersIndexes and EXPLAINTransactions, MVCC and locking
Pro
Roles, privileges and row-level securityBackups, replication and production
Tracks / PostgreSQL / Intermediate

JSONB, arrays and full-text search

PostgreSQL isn't only rows and columns. It can store and query JSON documents, arrays and searchable text, with indexes for all of them. Many apps that think they need a separate document store or search engine are well served by Postgres alone.

json vs jsonb

json jsonb
Stored as The exact text you gave it A parsed binary format
Keeps whitespace, key order, duplicate keys Yes No
Fast to query and index No Yes

Use jsonb. Plain json is only for keeping the exact original text.

Every editor in this lesson starts with this events table:

⚙️ Setup: this runs automatically in every editor below
sql
CREATE TABLE events (
  id      integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  type    text NOT NULL,
  payload jsonb NOT NULL
);

INSERT INTO events (type, payload) VALUES
  ('signup',   '{"user": {"id": 1, "name": "Asha"}, "plan": "pro", "tags": ["beta", "mobile"]}'),
  ('signup',   '{"user": {"id": 2, "name": "Rahul"}, "plan": "free", "tags": ["web"]}'),
  ('purchase', '{"user": {"id": 1, "name": "Asha"}, "amount": 49.5, "items": [{"sku": "MUG", "qty": 2}]}'),
  ('purchase', '{"user": {"id": 3, "name": "Li"}, "amount": 899, "items": [{"sku": "LAPTOP", "qty": 1}]}');
PostgreSQL · editable

Reading values

Operator Returns Example
-> jsonb payload -> 'user'
->> text payload ->> 'plan'
#> / #>> jsonb / text at a path payload #>> '{user,name}'
PostgreSQL · editable

->> gives text, so cast it (::numeric, ::int) before doing maths or comparisons.

Querying inside documents

PostgreSQL · editable

Building and changing JSON

PostgreSQL · editable
PostgreSQL · editable

JSON to rows: JSON_TABLE

JSON_TABLE (PostgreSQL 17+, standard SQL) turns JSON into a regular table you can join and filter:

PostgreSQL · editable

Indexing JSONB

A GIN index makes @>, ? and friends fast on millions of rows:

sql
CREATE INDEX events_payload_idx ON events USING gin (payload);

When to use JSONB (and when not)

✅ Good uses: data whose shape varies (webhook payloads, settings, form answers), and data you store and return as a whole.

❌ Not a replacement for columns: if you filter, join, or need constraints on a field, make it a real column. A common, healthy design has real columns for the important fields plus a jsonb column for the extras.

Arrays

Any type can be an array: text[], integer[]…

PostgreSQL · editable

unnest turns an array into rows. Arrays are great for small lists like tags; for anything with its own data (a tag with a description and colour), use a separate table.

Full-text search

LIKE '%word%' is slow on large tables and dumb: it doesn't know that "running" matches "run". Postgres has a real search engine built in:

  • A tsvector is a document processed into normalised words (lexemes).
  • A tsquery is a search query.
  • @@ means "matches".
PostgreSQL · editable

Stop words like "the" and "are" are dropped, and words are reduced to their stems ("foxes" → "fox", "running" → "run").

PostgreSQL · editable

websearch_to_tsquery accepts what users type into a search box: "exact phrase", -excluded, or. Title matches rank higher because of setweight('A'). Try searching for run.

Practice

  1. Find all purchase events where any item has "sku": "MUG" (hint: payload @> '{"items": [{"sku": "MUG"}]}').
  2. Count how many articles have each tag.
  3. Search docs for "search engine" (with quotes, as a phrase).
PostgreSQL · editable
✎ Check your understanding

1.What's the difference between -> and ->>?

2.Which should you use for most JSON columns?

3.Why is full-text search better than LIKE '%run%'?

← Postgres-powered SQL