Command Palette

Search for a command to run...

Hectal
Phase 7Intermediate8 of 18 in Database Design

Indexes and the Query Planner

B-tree, hash, GIN, GiST and BRIN indexes; composite index column order (equality, sort, range); covering, partial, expression and unique indexes; statistics and cost-based planning; and reading EXPLAIN ANALYZE.

Indexes are the biggest performance lever in a relational database and the most common source of wasted writes. This phase teaches you to derive indexes from queries and to confirm with the plan that they're used.

0/5 · 0%
5 topics ~41 min 7 code blocks & diagrams
Start with the first topic
1
7.1

Index Types: B-tree, Hash, GIN, GiST, BRIN

B-tree is the default and handles equality, ranges, sorting and prefix LIKE. Hash handles equality only. GIN indexes the elements inside values (JSONB keys, array elements, full-text lexemes). GiST supports ranges, geometry and nearest-neighbour. BRIN stores min/max per block range and is tiny, which suits huge append-only tables where values correlate with physical order.

8 min 1 code practice

2
7.2

Composite Index Mastery: Column Order and the Leftmost Prefix

A composite index (a, b, c) is sorted by a, then b within a, then c. It serves queries that constrain a leftmost prefix of the columns, with equality columns first, then the sort column, then a range column. A range on an earlier column stops later columns from narrowing the scan.

9 min 2 code practice

3
7.3

Covering, Partial, Expression and Unique Indexes, and Index Cost

Covering indexes (INCLUDE) let queries be answered from the index alone (index-only scans). Partial indexes cover just the rows queries care about. Expression indexes index a computed value. Unique indexes enforce rules. Every index costs write amplification, storage and cache, so unused and duplicate indexes should be dropped.

8 min 1 code practice

4
7.4

The Query Planner: Statistics, Selectivity, Scans and Joins

PostgreSQL's cost-based planner estimates how many rows each step returns (cardinality) from table statistics, assigns costs to candidate plans, and picks the cheapest. Scan types (sequential, index, index-only, bitmap) and join algorithms (nested loop, hash, merge) each win in different row-count regimes; wrong estimates lead to wrong choices.

8 min 1 code practice

5
7.5

Reading EXPLAIN ANALYZE

EXPLAIN shows the chosen plan with estimated costs and rows; EXPLAIN (ANALYZE, BUFFERS) runs the query and adds actual times, row counts, loops and buffer hits and reads. Read plans inside-out, compare estimated with actual rows to find misestimates, and look for the node where time and buffers concentrate.

8 min 2 code practice