🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Indexing: B-Tree, Hash, GiST, BRIN, Partial, Covering

Advanced SQLIndexing Strategies⭐ Premium

Interview Question: "When would you choose a BRIN index over a B-Tree? Explain covering indexes and index-only scans. How do partial indexes improve performance?" — Asked at Amazon, Pinterest, LinkedIn for Senior DBA roles

â„šī¸

Difficulty: Advanced | Companies: Amazon, Pinterest, LinkedIn, Uber, Netflix | Time: 45-60 minutes

B-Tree Index Structure

B-Tree maintains sorted data with balanced tree properties:

Where is branching factor and is number of keys.

Depth is only half the story. Because every point lookup descends from the root, the root page stays resident in shared_buffers after the first query, so an effective lookup is two cached reads plus one heap read. Inserts occasionally split a full leaf page and push a separator key upward; the default fillfactor of 90 leaves about a tenth of every page free so those splits are spread across the life of the index instead of clustering in the hour after a bulk load. Deletes do not collapse pages — they mark line pointers dead, which is why an update-heavy table slowly grows an index that only REINDEX can shrink.

-- Create table for indexing experiments
CREATE TABLE product_sales (
    sale_id SERIAL PRIMARY KEY,
    product_id INT,
    category VARCHAR(50),
    sale_date DATE,
    quantity INT,
    unit_price DECIMAL(10,2),
    total_amount DECIMAL(12,2),
    region VARCHAR(20),
    status VARCHAR(20)
);

-- Generate 10M rows
INSERT INTO product_sales (product_id, category, sale_date, quantity, unit_price, total_amount, region, status)
SELECT 
    (random() * 10000)::INT + 1,
    (ARRAY['Electronics', 'Clothing', 'Food', 'Books', 'Home'])[floor(random()*5+1)],
    CURRENT_DATE - (random() * 1000)::INT,
    (random() * 100)::INT + 1,
    (random() * 500)::DECIMAL(10,2),
    (random() * 50000)::DECIMAL(12,2),
    (ARRAY['North', 'South', 'East', 'West'])[floor(random()*4+1)],
    (ARRAY['completed', 'pending', 'refunded'])[floor(random()*3+1)]
FROM generate_series(1, 10000000);

B-Tree Index Operations

-- Standard B-Tree index
CREATE INDEX idx_product_sales_product ON product_sales(product_id);

-- Composite B-Tree index
CREATE INDEX idx_product_sales_composite ON product_sales(category, sale_date, total_amount);

-- Check index structure
SELECT 
    indexname,
    indexdef,
    pg_size_pretty(pg_relation_size(indexname::regclass)) AS index_size
FROM pg_indexes
WHERE tablename = 'product_sales';

-- Analyze index usage
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM product_sales 
WHERE product_id = 1234;

-- Range scan performance
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM product_sales 
WHERE category = 'Electronics' 
    AND sale_date BETWEEN '2024-01-01' AND '2024-12-31';

B-Tree Complexity:

OperationTime ComplexitySpace Complexity
Search
Insert
Delete
Range Scan

â„šī¸

Branch Factor: PostgreSQL B-Tree has ~400 keys per page with 8KB pages. Height of 3 can store ~64M keys.

A range scan is where that logarithm meets the data. O(log n + k) means the descent costs the same three page reads whether the table holds a million rows or a hundred million, and then the k matching entries arrive as a run of sibling leaf pages. A query returning 5,000 rows from a 250-entries-per-page index reads about 20 leaf pages on top of the descent — roughly 184 KB of index I/O. The sequential scan it replaces reads all of the heap, on the order of 100,000 pages for a 10 million row table of this shape. Which one wins depends on how many rows come back, and that trade-off is exactly what the cost model turns into numbers.

Hash Index

Hash indexes provide lookup for equality comparisons:

-- Hash index for equality lookups
CREATE INDEX idx_product_sales_hash_region ON product_sales USING hash(region);

-- Compare B-Tree vs Hash for equality
EXPLAIN (ANALYZE, BUFFERS)
SELECT COUNT(*) FROM product_sales WHERE region = 'North';

-- Hash index only works with equality operators
-- This will NOT use hash index:
EXPLAIN SELECT * FROM product_sales WHERE region > 'North';

Hash vs B-Tree Comparison:

FeatureHashB-Tree
Equality
RangeNot supported
OrderNot maintainedMaintained
MemoryHigherLower
WriteFasterSlower

Two constraints decide whether the hash index can be used at all. The first is equality only: region = 'North' uses it, while region > 'North', BETWEEN, ORDER BY region and a prefix match such as LIKE 'Nor%' cannot, because buckets carry no ordering. The second is history — hash indexes only became WAL-logged and crash-safe in PostgreSQL 10, so anything older must treat them as structures that can be rebuilt but not trusted after a crash. In exchange, a hash index on a 10 million row table is roughly the size of the key data itself, and a lookup is a single bucket probe instead of a three-level descent, which matters when the working set is too large to keep the tree hot in memory.

GiST Index for Complex Types

GiST (Generalized Search Tree) supports complex data types:

-- GiST index for range types
CREATE TABLE reservations (
    reservation_id SERIAL PRIMARY KEY,
    room_id INT,
    during TSRANGE,
    guest_name VARCHAR(100)
);

-- Create GiST index on range column
CREATE INDEX idx_reservations_during ON reservations USING gist(during);

-- Query for overlapping ranges
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM reservations 
WHERE during @> '2024-06-15'::date;

-- Find overlapping reservations
EXPLAIN (ANALYZE, BUFFERS)
SELECT r1.*, r2.* 
FROM reservations r1
JOIN reservations r2 ON r1.during && r2.during
WHERE r1.reservation_id < r2.reservation_id;

GiST Operator Classes:

TypeOperatorsUse Case
Range@>, <@, &&, <<, >>Temporal queries
Geometric@>, <@, &&, ~, @Spatial queries
Full-text@@, @>Text search
Array@>, <@Array containment

GiST indexes are lossy by design. For most operator classes the index returns a superset of candidates — an R-tree style bounding box in the spatial case, an interval overlap set in the range case — and the executor rechecks the exact predicate against the heap before returning a row. That recheck shows up in EXPLAIN as a filter layered on top of the index scan and is why GiST plans routinely report more rows read than the index seemed to match. The trade is deliberate: the alternative is storing exact geometry or exact intervals in every entry, which inflates the index and slows every insert. When the recheck filter eliminates most of the candidates, the index is giving you little and a sequential scan may be cheaper.

BRIN Index for Large Tables

BRIN (Block Range Index) stores min/max per block range:

-- BRIN index for time-series data
CREATE TABLE sensor_data (
    sensor_id INT,
    reading_time TIMESTAMPTZ,
    value DECIMAL(10,4)
);

-- Generate time-series data (correlated with insertion order)
INSERT INTO sensor_data
SELECT 
    (random() * 100)::INT + 1,
    NOW() - (random() * 365 * 24 * 60 * 60)::INT * INTERVAL '1 second',
    (random() * 100)::DECIMAL(10,4)
FROM generate_series(1, 10000000);

-- B-Tree index (large)
CREATE INDEX idx_sensor_btreen ON sensor_data(reading_time);
-- Size: ~200MB

-- BRIN index (small)
CREATE INDEX idx_sensor_brin ON sensor_data USING brin(reading_time)
    WITH (pages_per_range = 32);
-- Size: ~100KB

-- Compare performance
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM sensor_data 
WHERE reading_time BETWEEN '2024-06-01' AND '2024-06-30';

BRIN vs B-Tree Size Comparison:

RowsB-Tree SizeBRIN SizeRatio
1M21MB24KB875x
10M210MB240KB875x
100M2.1GB2.4MB875x

The mechanism behind that ratio is a table of summaries rather than a tree of keys. For each run of pages_per_range heap pages BRIN stores the minimum and maximum indexed value plus a tiny bitmap marking which pages inside the range could hold a match. A query for a single June discards every range whose maximum predates 1 June and every range whose minimum postdates 30 June, so the whole index can be read in a fraction of a millisecond and only the surviving ranges are visited. Because the summaries follow insertion order, a table appended in time order gives every range a narrow value span, while a table loaded in random order gives every range the full domain and nothing can be discarded. pages_per_range is the dial: raising it shrinks the index but widens each summary, lowering it does the reverse.

âš ī¸

BRIN Prerequisite: Data must be physically correlated with the indexed column. Random data makes BRIN ineffective.

Partial Index

Partial indexes reduce size by indexing only subset of rows:

-- Partial index for active orders only
CREATE INDEX idx_orders_active ON orders(order_date, total_amount)
WHERE status = 'pending';

-- Partial index with expression
CREATE INDEX idx_orders_high_value ON orders(total_amount)
WHERE total_amount > 10000;

-- Compare query plans
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders 
WHERE status = 'pending' AND order_date > '2024-01-01';

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders 
WHERE status = 'shipped' AND order_date > '2024-01-01';

-- Check partial index size
SELECT 
    indexname,
    pg_size_pretty(pg_relation_size(indexname::regclass)) AS size
FROM pg_indexes
WHERE tablename = 'orders'
    AND indexname LIKE 'idx_orders_%';

Partial Index Selectivity:

The planner will only use a partial index when it can prove that the query's WHERE clause implies the index predicate. A query filtering status = 'pending' matches the index defined on WHERE status = 'pending'; a query filtering status IN ('pending', 'shipped') does not, because shipped rows are provably outside the index; and neither does a filter on a parameter the planner cannot resolve at planning time. When the match succeeds the savings compound. With 1,000,000 orders of which 3% are pending, the index holds about 30,000 entries instead of a million, so it fits in a fraction of shared_buffers, and — the part people forget — an insert of a shipped order touches no index page at all instead of paying for a leaf update. The cost is one predicate implication check per query planner run.

Covering Index (INCLUDE)

Covering indexes include additional columns to enable index-only scans:

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

-- Query can be satisfied entirely from index
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, order_date, total_amount, status
FROM orders 
WHERE customer_id = 1234
    AND order_date > '2024-01-01';

-- Compare with non-covering index
CREATE INDEX idx_orders_non_covering ON orders(customer_id, order_date);

EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, order_date, total_amount, status
FROM orders 
WHERE customer_id = 1234
    AND order_date > '2024-01-01';

Index-Only Scan Benefits:

MetricTable ScanIndex ScanIndex-Only Scan
I/OHighMediumLow
CPULowMediumMedium
MemoryLowMediumHigh

An index-only scan reads the index and skips the heap only while the visibility map marks the underlying pages all-visible. A table that has just absorbed a large batch of updates has those bits cleared, so EXPLAIN ANALYZE starts printing Heap Fetches: in the hundreds of thousands and the index-only scan quietly becomes an index scan plus the random heap reads it was meant to avoid. Vacuum restores the bits, which is one way a neglected autovacuum schedule shows up as an indexing problem. The INCLUDE payload is not free either: those columns are stored in every leaf page, so adding a wide column to the payload can double the index size without indexing a single additional row.

â„šī¸

Covering Index Formula: For query with columns and , optimal covering index is:

Expression Index

-- Index on expression
CREATE INDEX idx_orders_upper_status ON orders(UPPER(status));

-- Index on function result
CREATE INDEX idx_orders_year ON orders(EXTRACT(YEAR FROM order_date));

-- Check if expression index is used
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders 
WHERE UPPER(status) = 'PENDING';

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders 
WHERE EXTRACT(YEAR FROM order_date) = 2024;

Two rules govern whether an expression index ever fires. The expression must be immutable, so UPPER(status) and EXTRACT(YEAR FROM order_date) qualify while anything reading the clock — CURRENT_DATE, now() — does not, and the planner will not match it. Second, the query must repeat the expression textually in a form the planner can canonicalise: WHERE UPPER(status) = 'PENDING' matches the index, while WHERE status = 'pending' never will, because the two are not the same predicate. Indexing a function also freezes its semantics — if you later decide EXTRACT should follow a fiscal calendar, the index and the query must change together.

Multi-Column Index Ordering

The order of columns in composite index matters:

-- Optimal column ordering for selective predicates
CREATE INDEX idx_product_category_date ON product_sales(category, sale_date);

-- This uses the index efficiently
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM product_sales 
WHERE category = 'Electronics' AND sale_date > '2024-01-01';

-- This only uses category prefix
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM product_sales 
WHERE category = 'Electronics';

-- This cannot use the index
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM product_sales 
WHERE sale_date > '2024-01-01';

Column order follows the shape of the query rather than the headline selectivity of the columns. Equality columns go first because they pin the seek to one contiguous slice, range columns go next so the scan can walk that slice in order, and any column that also satisfies ORDER BY comes last, letting the planner drop a sort node entirely. On the ten-million row sample spread across a thousand days, a one-year predicate such as category = 'Electronics' AND sale_date > '2024-01-01' walks about 730,000 entries through (category, sale_date) — 365 days at 2,000 Electronics rows per day — and about 3,650,000 through (sale_date, category), because the second form can only seek on the date and must then inspect all 10,000 rows landing in each day. The gap widens as the leading column gets more selective, which is why "add an index" is rarely the whole answer: the order inside the parentheses often decides more than the choice of columns.

Index Maintenance

-- Monitor index bloat
SELECT 
    indexname,
    pg_size_pretty(pg_relation_size(indexname::regclass)) AS size,
    idx_scan AS times_used,
    pg_size_pretty(pg_relation_size(indexname::regclass) - 
        (SELECT pg_relation_size(indexname::regclass) * 0.3)) AS bloat_estimate
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY pg_relation_size(indexname::regclass) DESC;

-- Rebuild bloated indexes
REINDEX INDEX idx_product_sales_composite;

-- Check index fragmentation
SELECT 
    indexname,
    round(100 * pg_relation_size(indexname::regclass) / 
        nullif(pg_relation_size('product_sales'::regclass), 0), 2) AS index_ratio
FROM pg_indexes
WHERE tablename = 'product_sales';

Index bloat is not the same as table bloat. A leaf page that is half dead still costs a full page read on every lookup, so an index that is 50% bloated behaves like an index built on twice as much data — the tree gets deeper, the cache hit rate falls, and the query planner's cost estimates stay blindly optimistic because they assume a healthy page fill. The index_ratio query above is the triage step: anything sitting at a large fraction of its table size is a rebuild candidate.

Rebuilding online means REINDEX CONCURRENTLY, which builds a complete second index alongside the first and then swaps names at the end. It needs free disk equal to the index being replaced and cannot run inside a transaction block, but it never blocks reads or writes. Plain REINDEX INDEX ... takes an exclusive lock instead and will hold up every query touching the table for as long as the rebuild runs, which on a large table is minutes rather than seconds. A third option is often the best one: indexes reporting idx_scan = 0 since the statistics reset are pure write tax, and dropping them improves insert throughput immediately.

Index Selection Algorithm

The optimizer evaluates indexes using:

Decision Matrix:

Query PatternRecommended IndexAvoid
Equality on 1 columnB-Tree or HashGiST
Range on 1 columnB-TreeHash
Equality + RangeComposite B-TreeSeparate indexes
Full-text searchGiST with tsvectorB-Tree
Large time-seriesBRINB-Tree
Low-selectivity filterPartial indexFull index

âš ī¸

Index Anti-Patterns:

  1. Over-indexing: Too many indexes slow down writes
  2. Wrong column order in composite indexes
  3. Not using partial indexes for filtered queries
  4. Ignoring index bloat and maintenance

Advanced: Index-Only Scan with Visibility Map

-- Check visibility map status
SELECT 
    relname,
    pg_size_pretty(pg_relation_size(relname::regclass)) AS table_size,
    pg_size_pretty(pg_total_relation_size(relname::regclass)) AS total_size,
    CASE 
        WHEN pg_relation_size(relname::regclass) > 1073741824 THEN 'Consider BRIN'
        WHEN pg_relation_size(relname::regclass) > 104857600 THEN 'Monitor bloat'
        ELSE 'OK'
    END AS recommendation
FROM pg_class
WHERE relkind = 'r'
    AND relnamespace = 'public'::regnamespace
ORDER BY pg_relation_size(relname::regclass) DESC
LIMIT 10;

â„šī¸

Pro Tip: Use pg_stat_user_indexes to find unused indexes. Drop them to improve write performance.

Common Mistakes

Building a composite index that leads with a range column while the equality predicate sits second

Fix: Order the columns equality, then range, then sort — the planner can only seek on a contiguous prefix of the index

Picking BRIN because the size comparison looks impressive, without checking how the table is loaded

Fix: Measure correlation between physical row order and the indexed column first; near-zero correlation makes every page range span the full value domain

Assuming an index-only scan stays index-only after heavy update traffic

Fix: Read Heap Fetches in EXPLAIN ANALYZE and keep autovacuum running so the visibility map marks pages all-visible again

Key Takeaways

  • B-tree depth grows so slowly that a point lookup costs a root, an internal and a leaf read even at tens of millions of keys
  • Hash indexes answer equality only and became crash-safe in PostgreSQL 10, while GiST deliberately returns lossy candidates that the executor rechecks
  • Partial indexes fire only when the query predicate implies the index predicate, and they save both read cost and writes on rows outside the subset
  • Composite order is equality, then range, then sort, then INCLUDE payload — the ordering inside the parentheses decides more than the column list does
🔒

Premium Content

Indexing: B-Tree, Hash, GiST, BRIN, 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