Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 115/ 160
06. Database Design, Normalization & Semi-Structured SQL

Indexing JSONB Columns with GIN Indexes

Speed up containment and key lookups on JSONB with GIN indexes.

AdvancedGIN · jsonb_path_ops3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

GIN remembers which documents contain which keys and values, so finding documents that contain something is fast.

Think of it like…

A GIN index is like the index at the back of a recipe book listing every ingredient: you can quickly find recipes that contain "basil". But if you ask "which recipes have exactly 2 cups of flour as their third ingredient", that index doesn't help; you'd need a different, purpose-built list.

Where you’ve seen it

An analytics events table with 300 million rows has properties jsonb. Product managers filter by plan and feature flag. A GIN index with jsonb_path_ops (much smaller than the default jsonb_ops index would have been) serves WHERE properties @> '{"plan": "pro", "beta": true}' in 40 ms, and an expression index on (properties->>'country') serves the country filter that the BI tool writes with ->>.

Words you’ll hear

jsonb_ops
Default GIN operator class: @>, ?, ?|, ?&, @?, @@.
jsonb_path_ops
Smaller, faster GIN class: @>, @? and @@ only (no key-existence operators).
Containment (@>)
Does the document contain this JSON fragment? The operator GIN is best at.
Expression index
A B-tree on (properties->>'country') for equality or range on one field.

Visual diagram

Loading interactive diagram

Theory & example queries

jsonb_ops vs jsonb_path_ops

CREATE INDEX ON events USING gin (properties) uses jsonb_ops, which indexes every key and every value separately. That supports key existence (properties ? 'coupon') as well as containment, but the index is large. CREATE INDEX ON events USING gin (properties jsonb_path_ops) hashes each full path-to-value into one entry, so the index is typically much smaller and containment lookups are faster, but ?, ?| and ?& can't use it.

Pick by query: if filters are containment checks and jsonpath, choose jsonb_path_ops; if you also need "documents that have key X", choose jsonb_ops. GIN scans return candidate rows that are rechecked, so the plan shows Bitmap Index Scan followed by Bitmap Heap Scan with a Recheck Cond.

Containment that uses the indexQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX events_props_gin ON events USING gin (properties jsonb_path_ops);23EXPLAIN4SELECT5  id6FROM7  events8WHERE9  properties @> '{"plan": "pro", "beta": true}';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative create and plan
CREATE INDEX Bitmap Heap Scan on events Recheck Cond: (properties @> '{"plan":"pro","beta":true}') -> Bitmap Index Scan on events_props_gin Index Cond: (properties @> '{"plan":"pro","beta":true}')

Note: A representative PostgreSQL plan. The optimizer may choose a sequential scan for low selectivity, and candidate rows still require a recheck.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

shows Bitmap Index Scan on events_props_gin.

Key takeaway: jsonb_path_ops for @> and jsonpath; jsonb_ops when you need ? key checks.

When GIN doesn't help, and costs

properties->>'plan' = 'pro' compares an extracted text value; GIN indexes can't serve it. Either rewrite it as containment (properties @> '{"plan": "pro"}'), which has the same meaning for a top-level string field, or add an expression index: CREATE INDEX ON events ((properties->>'plan')). Range filters such as (properties->>'amount')::numeric > 100 always need an expression B-tree, because containment can't express "greater than".

GIN indexes are expensive to update, since one document adds many entries. PostgreSQL buffers new entries in a pending list (fastupdate) and merges them later, which keeps inserts fast but can make some searches slower until the list is cleaned; gin_pending_list_limit and autovacuum control this. On write-heavy tables, index only the fields people filter on, for example with a partial index or expression indexes, rather than the whole document.

An expression index for a field the BI tool filters with ->>Query example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX events_country_idx ON events ((properties ->> 'country'));23SELECT4  COUNT(*)5FROM6  events7WHERE8  properties ->> 'country' = 'IN';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative create and count
CREATE INDEX count ----- 1284

Note: The row count is illustrative. Whether the COUNT uses an index scan, bitmap scan or sequential scan depends on data distribution and planner estimates.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

now uses an Index Scan or Bitmap Index Scan.

Key takeaway: ->> filters need expression B-trees; GIN has a write cost.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Queries

Collect the real query shapes

Check how the app, ORM and BI tools actually filter: @>, ?, ->> equality or ranges.

Focus at this step

@> · ? · ->> = · ->> >

What to watch at this step
Operator
decides the index
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A GIN index on a jsonb column indexes the keys and values inside every document, so containment queries such as properties @> '{"plan": "pro"}' become index lookups. PostgreSQL offers two operator classes: the default jsonb_ops supports @>, key-existence (?, ?|, ?&) and jsonpath operators; jsonb_path_ops supports only @> and jsonpath but is smaller and usually faster. Queries written as properties->>'plan' = 'pro' don't use either; they need an expression B-tree index.

Why it matters: JSON columns grow quickly and filters on them are a common source of full table scans. Picking the right index depends on exactly how queries are written, and many teams add a GIN index that their ORM's ->> filters never use. Knowing which operator matches which index is what makes JSON performant in production.

When to reach for it

  • Filtering events or products by JSON attributes
  • Feature-flag and plan filters on user properties
  • Searching documents with jsonpath conditions

When to avoid or be careful

  • Expecting GIN to speed up ->> comparisons
  • jsonb_path_ops when queries use ? to test keys
  • Whole-document GIN on write-heavy tables nobody filters

Indexing options for jsonb

GIN jsonb_ops (default)
Best for: Containment plus key-existence queries

Strengths: Supports the most operators.

Watch out: Largest index; slowest to update.

GIN jsonb_path_ops
Best for: Containment and jsonpath filters

Strengths: Smaller and usually faster for @>.

Watch out: No ?, ?| or ?& support.

Expression B-tree on one field
Best for: ->> equality, ranges and sorting on a known field

Strengths: Small; supports ORDER BY and ranges.

Watch out: One index per field; only that exact expression.

Interview signals & numbers to know

When this topic comes up

  • “Queries on our JSON column are slow”
  • “We added a GIN index but it isn't used”
  • “Find users whose properties contain plan = pro”
  • jsonb_path_ops
  • Expression indexes

Benchmarks & rules of thumb

2 -
GIN operator classes for jsonb
@> -
the operator both classes support
0 -
GIN indexes usable by ->> = 'x'

Common mistakes & follow-ups

Common interview mistakes

  • Creating a GIN index while the ORM generates WHERE properties->>'plan' = 'pro', so every query still scans.
  • Switching to jsonb_path_ops and breaking the performance of WHERE properties ? 'coupon'.
  • Filtering on (properties->>'amount')::numeric > 100 and expecting containment or GIN to help.

Likely interviewer follow-ups

  • Why isn't my GIN index used for properties->>'plan' = 'pro'?
  • jsonb_ops or jsonb_path_ops: how do you choose?
  • How do you index a numeric range filter on a JSON field?
Interview tip: Name the query's operator first, then the index that matches it. Saying "->> needs an expression index, @> uses GIN" shows you've debugged this for real.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Indexing JSONB Columns with GIN Indexes with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Querying JSON Objects & Arrays (->, ->>, #>, @>, jsonb_each, jsonb_array_elements)
Next topic
Working with SQL Arrays (ARRAY_AGG, UNNEST, ANY, Array Operators)