🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Advanced Indexing — B-Tree, GIN, GiST, Partial & Covering

Advanced SQLPerformance⭐ Premium

Advanced Indexing Strategies

Advanced SQL

Index Like a Pro

Indexes are the single most impactful performance tool in SQL. The right index can turn a 30-second query into a 30-millisecond one. But choosing the wrong index wastes space and slows writes.

  • B-Tree — Default for equality and range queries
  • GIN — Inverted index for arrays, JSON, full-text search
  • GiST — Geospatial and range types
  • BRIN — Block range index for large, naturally ordered tables
  • Partial — Index only a subset of rows

The key to indexing: understand your query patterns, then create indexes that match them.


Index Types at a Glance

B-TreeEquality: = Range: <, >, BETWEENSort: ORDER BYLIKE 'abc%'Default choiceMost queriesBalanced R/WGINArrays: @>, &&JSONB: @?, @@Full-text: @@ContainsSemi-structuredSlow writesFast readsGiSTGeospatial: &&Range typesNearest neighborST_DWithinSpatial dataApproximateLossyBRINTime-seriesAppend-onlyNatural orderTiny index sizeLarge tablesBlocks-levelMin/max per blockPartialWHERE activeWHERE status='new'Selective rowsSmaller indexSubset queriesTiny & fastWHERE clause match

B-Tree Index Fundamentals

-- Standard B-tree index
CREATE INDEX idx_users_email ON users (email);

-- Composite B-tree index (column order matters!)
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date DESC);

-- Unique constraint (creates unique B-tree index)
ALTER TABLE users ADD CONSTRAINT uk_users_email UNIQUE (email);

ℹ️

Key Insight: B-tree indexes support equality and range queries. The column order in composite indexes matters: put equality columns first, then range columns, then sorting columns.

A composite index is not two indexes bolted together — it is one sorted structure in which customer_id is the major key and order_date the minor key. A predicate on customer_id can seek to one contiguous block and walk it; a predicate on order_date alone cannot use the stored order at all, because the dates are only sorted within each customer. The practical rule is that an index answers questions about a prefix of its column list, and every column positioned after a range predicate becomes payload rather than search key.

The physical shape explains why this is cheap. At the default 8 KB page size and roughly 20 to 30 bytes per composite entry, a leaf page carries 250 to 400 keys, so a point lookup on a ten-million row table costs one root page, one internal page, one leaf page and then the heap — three mostly cached reads plus one random read before the predicate is even evaluated. That is also why the first column of the index matters more than the last three combined: it decides which single leaf page out of tens of thousands you end up reading.


Partial Indexes

-- Index only active users (smaller & faster)
CREATE INDEX idx_active_users ON users (email)
WHERE status = 'active';

-- Index recent orders
CREATE INDEX idx_recent_orders ON orders (customer_id, order_date)
WHERE order_date > CURRENT_DATE - INTERVAL '90 DAY';

-- Index pending tasks
CREATE INDEX idx_pending_tasks ON tasks (assigned_to, priority)
WHERE status = 'pending';

A partial index is used only when the planner can prove the query implies the index predicate, which is a real proof obligation rather than a string match. WHERE status = 'pending' satisfies it directly; WHERE status = 'pending' AND priority = 'high' also satisfies it, because anything matching both certainly matches the first; and WHERE status IN ('pending', 'running') fails it, because running rows are provably absent from the index. The size effect scales with the subset — on a million rows where 4% are pending, the index holds about 40,000 entries instead of a million, fits in a far smaller slice of the buffer cache, and, the part that is easy to overlook, never receives a write when a running row is inserted.


GIN Index for Arrays and JSON

-- GIN index for array containment
CREATE INDEX idx_user_tags ON users USING GIN (tags);

-- GIN index for JSONB
CREATE INDEX idx_user_data ON users USING GIN (data);

-- GIN with specific operator class (smaller, faster)
CREATE INDEX idx_user_data_path ON users USING GIN (data jsonb_path_ops);

GIN inverts the relationship between row and value: instead of mapping a row to its values, it maps each distinct element — an array member, a JSON key, a lexeme — to the list of rows containing it. That is why containment and existence tests are fast and why a query that does not reduce to containment gets nothing from the index at all. Two operational costs come with the design. Entries stage in a pending list that a background cleanup must flush, so under constant write the index can lag the table by a short interval unless fast update is turned off. And a single row may be reached through thousands of elements, so a filter on a very common value returns a huge candidate set that the executor rechecks row by row — selectivity of the predicate, not the size of the index, decides whether GIN helps. The jsonb_path_ops operator class stores one hash per document instead of every key and value, which shrinks the index substantially while supporting containment only.


GiST Index for Geospatial

-- GiST index for geometric data
CREATE INDEX idx_locations ON stores USING GiST (
  ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
);

-- GiST index for range types
CREATE INDEX idx_booking_dates ON bookings USING GiST (
  tsrange(check_in, check_out)
);

GiST is a framework rather than a single structure: the same balanced-tree machinery backs geometric bounding boxes, interval ranges, text-search vectors and point clouds, each supplying a consistency function that decides which branches can still contain a match. That indirection is what makes GiST queries finish with a recheck — the tree narrows the candidate set using an approximate test, and the executor confirms the survivors against the heap — and it is also why GiST entries are larger and slower to build than B-tree entries holding the same keys. What the framework buys is the operators a B-tree cannot express: overlap, containment in either direction, and nearest-neighbour ordering through a distance operator, which is what lets a plan answer ORDER BY location <-> centre LIMIT 20 without sorting the whole table.


Expression Indexes

-- Index on function result
CREATE INDEX idx_users_lower_email ON users (LOWER(email));

-- Index on computed value
CREATE INDEX idx_orders_total ON orders (
  (quantity * unit_price * (1 - discount))
);

-- Index on date extraction
CREATE INDEX idx_orders_month ON orders (EXTRACT(MONTH FROM order_date));

⚠️

Performance Tip: Expression indexes are only used when the query uses the exact same expression. Make sure your query matches the index definition precisely — LOWER(email) = 'test' uses the index, but email = 'TEST' does not.


Covering Indexes (INCLUDE)

-- Covering index with INCLUDE (avoids table lookups)
CREATE INDEX idx_orders_covering ON orders (customer_id, order_date)
INCLUDE (total_amount, status);

-- Verify index-only scan
EXPLAIN (ANALYZE)
SELECT order_date, total_amount, status
FROM orders
WHERE customer_id = 123;

INCLUDE columns are stored in the leaf pages only and never participate in seeking or sorting, which is exactly why they are cheaper than appending the same columns to the key: the payload widens the leaves without widening the search path, so the tree depth and the entry comparison cost stay where they were. The benefit is visible as a heap-fetch count of zero in EXPLAIN ANALYZE for as long as the visibility map still marks the underlying pages all-visible. Once a heavy update batch clears those bits, the count climbs and the scan quietly degrades into an index scan with the same random heap reads it was designed to avoid — which is why the maintenance statement and the covering index belong in the same review.


BRIN Index for Large Tables

-- Block Range Index for time-series data (tiny index size)
CREATE INDEX idx_events_timestamp ON events USING BRIN (event_time);

-- BRIN with custom page range
CREATE INDEX idx_logs_time ON logs USING BRIN (created_at)
WITH (pages_per_range = 32);

The choice can be measured before the index exists. SELECT correlation FROM pg_stats on the indexed column answers the only question that matters: a value near 1.0 or -1.0 means physical order follows the values, every page range has a narrow min and max, and range predicates discard almost the whole index; a value near 0 means every range spans the domain and the index degenerates into extra I/O on top of the scan. pages_per_range then trades size against precision — the default of 128 suits most append-only tables, halving it roughly doubles the index while narrowing each summary, and raising it does the reverse. A BRIN index over a hundred million rows can sit in a few megabytes, so this tuning loop costs almost nothing to run twice.


Multi-Column Index Strategy

-- Optimal column order:
-- 1. Equality predicates (status = 'active')
-- 2. Range predicates (order_date > '2024-01-01')
-- 3. Sort columns (ORDER BY customer_id)
-- 4. SELECT list columns (INCLUDE for covering)

CREATE INDEX idx_optimal ON orders (
  status,           -- Equality
  order_date,       -- Range
  customer_id       -- Sort
) INCLUDE (total_amount);

Equality leads because an equality predicate pins the scan to one contiguous region of the index, after which a range predicate can be followed in stored order without a sort. Reverse the two and the same query must visit one region per value of the range column: with orders spanning 500 days in four statuses, the predicate status = 'shipped' AND order_date > '2024-06-01' reads a single contiguous block through (status, order_date) but must touch every status's entries for the period through (order_date, status) — roughly four times the index I/O to return identical rows. Sort columns belong third because a scan that ends where ORDER BY wants lets the planner drop a sort node entirely, and the INCLUDE payload comes last because it is read but never searched.


Index Maintenance

-- Check index size
SELECT indexname, pg_size_pretty(pg_relation_size(indexname::regclass)) AS size
FROM pg_indexes WHERE tablename = 'employees';

-- Rebuild bloated indexes
REINDEX INDEX idx_users_email;

-- Check index usage statistics
SELECT indexrelname, idx_scan, idx_tup_read, idx_tup_fetch,
  pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'employees'
ORDER BY idx_scan DESC;

Concurrent Index Creation

-- Create index without locking table (production-safe)
CREATE INDEX CONCURRENTLY idx_large_table ON large_table (column_name);

-- Check for invalid indexes
SELECT indexrelname, indisvalid, indisready
FROM pg_stat_user_indexes
INNER JOIN pg_index ON indexrelid = pg_stat_user_indexes.indexrelid
WHERE NOT indisvalid;

Building concurrently runs in three phases: catalog entry, an initial scan that writes entries while ordinary reads continue, and a second scan that waits for transactions still holding the pre-build snapshot to finish before marking the index valid. Two consequences follow. The command cannot run inside a transaction block, so wrapping it in a migration that has already opened one fails immediately with a clear error rather than half-completing. And if any phase dies — a lock conflict, a dropped connection, an admin who cancelled the statement — PostgreSQL leaves the index behind marked invalid. It still occupies disk, the planner ignores it, and every retry of CREATE INDEX CONCURRENTLY fails until the invalid index is dropped first, which is precisely what the check query above exists to find.


Quiz: Test Your Knowledge


Follow-Up Questions

  1. When would you choose a GIN index over a B-tree index?
  2. How do partial indexes improve query performance?
  3. Explain the difference between GiST and SP-GiST indexes.
  4. How do you determine the optimal column order for composite indexes?
  5. What's the impact of index maintenance on write performance?

Common Mistakes

Designing a composite index and then writing the query so its leading predicate is the range column

Fix: Lead with equality columns, then range, then sort — the index can only seek on a contiguous prefix, and a range first makes every later column unreachable for searching

Assuming any query that mentions the indexed column will pick up a partial index

Fix: The planner must prove the query implies the index predicate; an IN list covering values outside the subset, or a parameter it cannot resolve, disqualifies it

Retrying CREATE INDEX CONCURRENTLY after a failure without removing what the failed attempt left behind

Fix: Drop the index marked indisvalid = false first, then rerun the build — the check against pg_index is the step that saves the second attempt

Key Takeaways

  • B-Tree — Default choice for equality, range, and sort queries
  • GIN — Best for arrays, JSONB, and full-text search (inverted index)
  • GiST — Geospatial, range types, nearest-neighbor searches
  • BRIN — Tiny indexes for large, naturally ordered tables (time-series)
  • Partial — Index only a subset of rows (WHERE clause) — smaller & faster
  • Covering — INCLUDE columns to avoid table lookups (index-only scan)
  • Column order — Equality → Range → Sort → INCLUDE
🔒

Premium Content

Advanced Indexing — B-Tree, GIN, GiST, Partial & Covering

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement