Without an index, a lookup by order number reads the whole table; with one, it reads a handful of pages.
A relational table is stored as a heap: a file made of fixed-size pages, 8 KB each in a default PostgreSQL build, with rows placed wherever there is room. Inside the engine a row version is called a tuple. A heap has no order. Rows are not sorted by any column, and an UPDATE may write the new version of a row into a different page from the old one.
Every tuple has a physical address called its ctid: the page number and the item number inside that page. An index is a second structure that maps a key value to ctids. Later lessons build indexes, so it helps to see ctids first.
The database does its input and output in whole pages. To use one row, the server must bring its page into shared buffers, the cache of pages in the server's memory. The cost of most queries is therefore the number of pages they touch, which is why this lesson counts pages and not rows.
The whole chapter uses one table, orders, a trimmed version of the grocery delivery orders table with a total column added. Ten lakh rows are generated with fixed arithmetic, so every run produces the same data: 40 stores, 50,000 customers, and one order every 30 seconds from 1 January 2026. The last 5,000 orders are placed, every fiftieth order is cancelled, and the rest are delivered. There is no primary key yet, on purpose. Every run in this chapter is on a local PostgreSQL 18.6 server.
sql
CREATETABLE orders (
order_id int NOTNULL,
customer_id int NOTNULL,
store_id int NOTNULL,
placed_at timestamptz NOTNULL,
status text NOTNULL,
total numeric(10,2) NOTNULL
);
INSERTINTO orders (order_id, customer_id, store_id, placed_at, status,
total)
SELECT i,
(i::bigint * 7919 % 50000)::int + 1,
i % 40 + 1,
timestamptz '2026-01-01 00:00:00+05:30' + i * interval
'30 seconds',
CASEWHEN i > 995000THEN'placed'WHEN i % 50 = 0THEN'cancelled' ELSE 'delivered'END,
100 + (i * 37) % 900FROM generate_series(1, 1000000) AS g(i);
Results are printed with the helper from the SQL chapter, so NULL shows as NULL.
Counting the pages of a table
The server can report how many bytes a table occupies. Dividing by the page size gives the number of pages, and a query on ctid shows how many rows fit in each one.
sql
SELECT pg_relation_size('orders') AS bytes,
pg_relation_size('orders') / 8192AS pages,
(SELECT count(*) FROM orders) AS row_count;
The table holds 8,334 pages, about 68 MB, which is close to 68 bytes per row once page overhead is counted. The next query casts the ctid to a point to pull out its page number, and counts the rows in the first three pages.
sql
SELECT (ctid::text::point)[0]::int AS page, count(*) AS rows_on_page
FROM orders
WHERE (ctid::text::point)[0] IN (0, 1, 2)
GROUPBY1ORDERBY1;
The first three orders sit in page 0, items 1 to 3. Order 500000 sits at page 4,166, item 80, and 4,166 times 120 plus 80 is exactly 5,00,000. The table was loaded in order of order_id, so the rows happen to lie in that order on disk. Nothing in a heap guarantees this. After updates and deletes, the same table would have rows out of order, and a query must never assume otherwise.
A lookup without an index
Now ask for one order by its number. The first statement turns off parallel workers, which are extra processes the planner may add to share the pages of a large scan. With them off, one process reads the table, and the plan is easier to read. EXPLAIN (ANALYZE, BUFFERS) runs the query and reports what happened, and COSTS OFF and SUMMARY OFF hide planner estimates and totals that this lesson does not use.
sql
SET max_parallel_workers_per_gather = 0;
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY OFF)
SELECT order_id, placed_at, status FROM orders WHERE order_id = 777777;
text
QUERY PLAN
-----------------------------------------------------------------
Seq Scan on orders (actual time=35.683..44.094 rows=1.00 loops=1)
Filter: (order_id = 777777)
Rows Removed by Filter: 999999
Buffers: shared hit=8334
(6 rows)
Timings are from one run on this machine and vary from run to run.
Read the plan from the top. A Seq Scan (sequential scan) reads every page of the table in order and tests each row against the Filter. Rows Removed by Filter: 999999 says that all rows but the one wanted were read and thrown away. Buffers: shared hit=8334 says the scan touched 8,334 buffers, which is exactly the number of pages in the table. hit means the page was already in shared buffers. A page that has to come from the operating system or disk is counted as read instead. Hits and reads say how warm the cache was, not what the plan did, so compare the total of the two when you compare plans.
The line actual time=35.683..44.094 gives the time in milliseconds to the first row and to the end. On this machine the scan took tens of milliseconds, and the figure moves from run to run. PostgreSQL 18 also prints rows=1.00 with decimals, because the figure is an average per loop.
Two more probes show that the cost follows the table, not the answer.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY OFF)
SELECT order_id, placed_at, status FROM orders WHERE order_id = 0;
text
QUERY PLAN
-----------------------------------------------------------------
Seq Scan on orders (actual time=45.073..45.074 rows=0.00 loops=1)
Filter: (order_id = 0)
Rows Removed by Filter: 1000000
Buffers: shared hit=8334
(4 rows)
An order number that does not exist finds no rows, yet the scan still reads all 8,334 pages, because the only way to prove absence is to look at everything. The opposite case needs an order near the start of the table.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY OFF)
SELECT order_id, placed_at, status FROM orders WHERE order_id = 5LIMIT1;
With LIMIT 1 the scan stops as soon as it has a row. Order 5 is in the first page, and the scan touched two buffers. The count is two where one page was needed, and this chapter does not explain the second buffer. A sequential scan is cheap when the wanted row happens to come early, and costs the whole table when it does not. The next lesson builds the structure that makes the cost small whichever row you ask for.
Check yourself
The orders heap has 8,334 pages. Roughly how many buffers does WHERE order_id = 0 touch when no row matches, and why?
About 8,334, the same as for a row that exists.
A sequential scan can only prove that a row is absent by reading every page, so the number of matches does not change the cost.
What does Buffers: shared hit=8334 tell you, and what would read= mean?
hit counts pages found in shared buffers, so the scan did not go to the operating system for them.
read counts pages fetched from outside shared buffers. The sum of the two is the number of pages the scan touched.
Order 500000 has the ctid (4166,80). What does that mean, and can you rely on rows staying in order_id order?
Page 4,166 of the heap, item 80 on that page.
No. The load happened to place rows in order, but a heap has no guaranteed order and updates may move rows.
Part 2 · B-tree structure
What a B-tree index is
An index is a separate structure that stores the values of some columns together with the ctid of each row, in sorted order, so the server can find a key without reading the table. CREATE INDEX builds a B-tree unless you name another method. PostgreSQL's B-tree is a multi-way balanced tree: pages hold many entries, and every path from the top to the bottom has the same length.
The index file starts with a metapage that records where the tree begins. The other pages are leaf pages, on the lowest level, which hold one entry per row (the key and the row's ctid), and internal pages, which hold a key bound and a downlink, the number of a child page, for each child. The topmost internal page is the root. Each level is also a doubly linked list, so a range scan can move sideways between leaves. The documentation says that over 99 percent of the pages are leaves.
A lookup reads the root, follows one downlink per page until it reaches a leaf, and takes the ctid from there. One more read, in the heap, returns the row. When a leaf has no room for a new entry it splits in two and the parent gains a downlink. When the root overflows, a new root is created above it. The tree only grows at the top, so all leaves stay at the same depth and the height grows with the logarithm of the number of rows.
Building one and looking inside
Create a unique B-tree on order_id. The pageinspect extension, which ships with the server, reads index pages directly: bt_metap shows the metapage and bt_page_stats describes one page.
sql
CREATE EXTENSION IF NOTEXISTS pageinspect;
sql
CREATE UNIQUE INDEX orders_order_id_idx ON orders (order_id);
sql
SELECT pg_relation_size('orders_order_id_idx') AS bytes,
pg_relation_size('orders_order_id_idx') / 8192AS pages;
The index takes 2,745 pages, about 22 MB, against 8,334 for the table. level is the level of the root, 2, where leaves are level 0: a lookup passes a level 2 page, a level 1 page and a leaf. The next query counts pages by type.
sql
SELECT s.type, count(*) AS pages,
round(avg(s.live_items), 1) AS avg_items,
round(avg(s.avg_item_size), 1) AS avg_item_bytes
FROM generate_series(1,
pg_relation_size('orders_order_id_idx') / 8192 - 1) AS p(n),
LATERAL bt_page_stats('orders_order_id_idx', p.n::int) AS s
GROUPBY s.type
ORDERBY s.type;
text
type | pages | avg_items | avg_item_bytes
-----+-------+-----------+---------------
i | 10 | 274.2 | 15.0
l | 2733 | 366.9 | 16.0
r | 1 | 10.0 | 15.0
(3 rows)
Type l is a leaf, i an internal page, r the root. There are 2,733 leaves with about 367 entries each, which is 99.6 percent of the pages, in line with the documentation. Each entry is 16 bytes here. The root has 10 entries, one per internal page.
Searching the tree
With the index in place, the lookup from the previous lesson changes. The Index Searches line is new in PostgreSQL 18 and counts the descents of the tree.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY OFF)
SELECT order_id, placed_at, status FROM orders WHERE order_id = 777777;
text
QUERY PLAN
------------------------------------------------------------------------
Index Scan using orders_order_id_idx on orders (actual time=0.013..0.013
rows=1.00 loops=1)
Index Cond: (order_id = 777777)
Index Searches: 1
Buffers: shared hit=4
(6 rows)
Four buffers: three index pages (root, internal, leaf) and one heap page, against 8,334 for the sequential scan. A key that does not exist is cheaper still.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, SUMMARY OFF)
SELECT order_id, placed_at, status FROM orders WHERE order_id = 0;
text
QUERY PLAN
------------------------------------------------------------------------
Index Scan using orders_order_id_idx on orders (actual time=0.015..0.015
rows=0.00 loops=1)
Index Cond: (order_id = 0)
Index Searches: 1
Buffers: shared hit=3
(4 rows)
Three buffers. The leaf shows that the key is missing, so no heap page is read. Unlike in a heap, a miss costs no more than a hit.
A tree small enough to see
To see a whole tree, make the entries large. In the table below every key is about 1.5 KB, so a page holds only a few, and 24 rows need three levels. The keys come from md5 text so that they do not compress: a first attempt with a repeated letter compressed so well that every key fitted on one page.
sql
CREATETABLE fat (code text NOTNULL, note text);
INSERTINTO fat (code, note)
SELECT lpad(i::text, 3, '0') ||
(SELECT string_agg(md5(i::text || k::text), '')
FROM generate_series(1, 47) AS k),
'row ' || i
FROM generate_series(1, 24) AS g(i);
CREATEINDEX fat_code_idx ON fat (code);
sql
SELECT level, root FROM bt_metap('fat_code_idx');
text
level | root
------+-----
2 | 9
(1 row)
sql
SELECT itemoffset AS item, ctid AS child
FROM bt_page_items('fat_code_idx', 9) ORDERBY itemoffset;
SELECT p.n AS leaf_page, count(*) AS entries, min(left(f.code, 3))
AS first_key, max(left(f.code, 3)) AS last_key
FROM generate_series(1, 7) AS p(n),
LATERAL bt_page_items('fat_code_idx', p.n::int) AS i
JOIN fat f ON f.ctid = i.htid
WHERE p.n IN (1, 2, 4, 5, 6, 7)
GROUPBY p.n
ORDERBY p.n;
The metapage says the root is page 9, at level 2. It has two entries, pointing to internal pages 3 and 8. Page 8 points to leaves 6 and 7. Page 3 has five items, and the first is not a downlink: the pageinspect documentation says that the first item on any page that is not the rightmost on its level is a high key, an upper bound for the keys on that page. The other four items point to leaves 1, 2, 4 and 5. Pages 8 and 9 are the rightmost on their levels and have no high key. The leaves hold four keys each, 001 to 024.
The lookup needs the 1.5 KB key of row 17 more than once, so a small function builds it. The planner would read a 24-row table directly, so sequential scans are off for this one run, and a prepared statement with a forced generic plan keeps the key a parameter.
sql
CREATEOR REPLACE FUNCTION fat_code(n int) RETURNS text LANGUAGE sql
IMMUTABLE
AS'SELECT lpad(n::text, 3, ''0'') ||
(SELECT string_agg(md5(n::text || k::text), '''')
FROM generate_series(1, 47) AS k)';
sql
SET enable_seqscan = off;
SET plan_cache_mode = force_generic_plan;
sql
PREPARE find (text) ASSELECTleft(code, 3) ASkey, note FROM fat
WHERE code = $1;
QUERY PLAN
---------------------------------------------------------------
Index Scan using fat_code_idx on fat (actual rows=1.00 loops=1)
Index Cond: (code = $1)
Index Searches: 1
Buffers: shared hit=4
(6 rows)
The settings above are reset with RESET afterwards.
Looking up row 17 reads four buffers: root, internal page 8, leaf 6 and one heap page. The scene replays that walk.
Animated sceneOne lookup down a B-tree0:19
Watch for the search touching one page per level on its way to key 017
Read it as steps
Watch for the search touching one page per level on its way to key 017.
One page per level, and nothing else was read: the other five leaves cost nothing.
How deep can a tree get
Depth comes from fan-out, the number of entries per page. In the order index a leaf holds about 367 entries and an internal page about 274 downlinks. The scene redoes the arithmetic with the measured numbers.
Animated sceneWhy ten lakh keys need three pages0:16
Pages read for one lookup: 3 + 1 (3 index pages and 1 heap page)
Read it as steps
The page counts come from the run on the order_id index.
The estimate lands close to the measured 2,733 leaves and 10 internal pages. One internal page covers 274 leaves, roughly one lakh keys, and a root with room for about 274 downlinks would cover about 2.7 crore keys in the same three levels. That last step is arithmetic, not a run. Each level multiplies capacity by a few hundred. An entry cannot exceed about a third of a page, so very wide keys, like the fat table's, cut the fan-out and deepen the tree.
The order_id index has level 2 and a lookup reported Buffers: shared hit=4. Where do the four buffers come from?
Three index pages (root, one internal page, one leaf) and one heap page that holds the row.
The lookup for an order number that does not exist touched three buffers. Why not four?
The leaf page shows that the key is missing, so the heap page is never visited.
Why does ten times more data usually not mean ten times more page reads?
Each page holds hundreds of entries, so a new level multiplies capacity by a few hundred.
The tree gets deeper only when the data outgrows the root.
Part 3 · Composite indexes
Indexes on more than one column
Most real queries filter on more than one column: orders of one store in one day, or one customer's open orders. A composite index (also called a multicolumn index) is a B-tree whose key has several columns. Its entries are sorted by the first column, and entries with the same first value are sorted by the second, and so on, like a phone book sorted by surname and then by first name.
That ordering decides what the index can do. The documentation states the rule: equality constraints on the leading columns, plus any inequality constraint on the first column without an equality constraint, limit the part of the index that is scanned. Constraints on columns further right are still checked inside the index, which saves table visits, but they do not shrink the part that must be read.
Two practical rules follow. Put the columns that the query compares with = first, and the column used for a range (>, <, BETWEEN) last. And the index serves any query that constrains a prefix of its columns, so an index on (store_id, placed_at) also serves queries that filter on store_id alone, and it hands rows back already sorted by placed_at for one store.
PostgreSQL 18 added skip scan, which lets a query that does not constrain the leading column still use the index. The planner can generate an equality condition for every distinct value of the leading column and combine it with the condition on the later column, so the index is searched repeatedly. The documentation says this is chosen mainly when the leading column has few distinct values.
A small index you can see through
A table of 16 rows is enough to see the order of the entries. It records orders per store per day for four stores and four days, with an index on (store_id, day).
sql
CREATETABLE slots (store_id int NOTNULL, day int NOTNULL, orders int
NOTNULL);
INSERTINTO slots (store_id, day, orders)
SELECT s, d, s * 10 + d
FROM generate_series(1, 4) AS a(s), generate_series(1, 4) AS b(d);
CREATEINDEX slots_idx ON slots (store_id, day);
sql
SELECT store_id, day FROM slots ORDERBY store_id, day;
This is the order of the index entries: all of store 1, then all of store 2, and inside each store the days in order. Now ask for store 3, days 2 and 3. A table this small would be read directly, so the plan below disables the other scan types to make the planner use the index.
sql
SET enable_seqscan = off;
SET enable_bitmapscan = off;
sql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT store_id, day, orders FROM slots WHERE store_id = 3AND day BETWEEN2AND3;
text
QUERY PLAN
--------------------------------------------------------------
Index Scan using slots_idx on slots (actual rows=2.00 loops=1)
Index Cond: ((store_id = 3) AND (day >= 2) AND (day <= 3))
Index Searches: 1
(3 rows)
sql
SELECT store_id, day, orders FROM slots WHERE store_id = 3AND day BETWEEN2AND3ORDERBY day;
The Index Cond has all three conditions, and a single index search is enough: the entries wanted sit next to each other. The scene follows the 16 entries in order.
Animated sceneA range scan inside one store0:18
Watch for the scan going straight to store 3, day 2, and stopping after day 3
Read it as steps
Watch for the scan going straight to store 3, day 2, and stopping after day 3.
The entries for stores 1 and 2 are never read, and the scan stops at the first entry beyond day 3. That is what equality first and range last buys: the matching entries form one unbroken run. With the day first, the wanted entries would be spread across the index.
Composite indexes on ten lakh orders
Back to the orders table, with the equality column first. Each statement below was run once beforehand, so the figures are warm-cache figures, and the session time zone is Asia/Kolkata.
sql
CREATEINDEX orders_store_time_idx ON orders (store_id, placed_at);
Orders of store 7 on 1 March 2026 use both columns. The day is a half-open range.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, total FROM orders
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders (actual rows=72.00 loops=1)
Recheck Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Blocks: exact=24
Buffers: shared hit=28
-> Bitmap Index Scan on orders_store_time_idx (actual rows=72.00
loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Index Searches: 1
Buffers: shared hit=4
(10 rows)
The query returns 72 rows. A Bitmap Index Scan collects the ctids of the matching entries into a bitmap, and the Bitmap Heap Scan then reads the heap pages in page order, once each. One index search found all 72 entries. The 28 buffers are 4 index pages and 24 heap pages: the 72 orders are spread over 24 pages because the 40 stores alternate in the heap.
A query on the leading column alone also uses the index. This one asks for the three oldest orders of store 7. The entries of one store are already sorted by time, so no sort is needed and the scan stops after three rows.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, placed_at FROM orders WHERE store_id = 7ORDERBY placed_at LIMIT3;
text
QUERY PLAN
------------------------------------------------------------------------
Limit (actual rows=3.00 loops=1)
Buffers: shared hit=4
-> Index Scan using orders_store_time_idx on orders (actual rows=3.00
loops=1)
Index Cond: (store_id = 7)
Index Searches: 1
Buffers: shared hit=4
(8 rows)
Now the skip scan: a query on the day without the store.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, total FROM orders
WHERE placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders (actual rows=2880.00 loops=1)
Recheck Cond: ((placed_at >= '2026-03-01 00:00:00+05:30'::timestamp
with time zone) AND (placed_at < '2026-03-0200:00:00+05:30'::timestamp with time zone))
Heap Blocks: exact=25
Buffers: shared hit=175
-> Bitmap Index Scan on orders_store_time_idx (actual rows=2880.00
loops=1)
Index Cond: ((placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Index Searches: 42
Buffers: shared hit=150
(8 rows)
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, total FROM orders
WHERE placed_at >= '2026-03-01 10:00'AND placed_at <
'2026-03-01 11:00';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders (actual rows=120.00 loops=1)
Recheck Cond: ((placed_at >= '2026-03-01 10:00:00+05:30'::timestamp
with time zone) AND (placed_at < '2026-03-0111:00:00+05:30'::timestamp with time zone))
Heap Blocks: exact=2
Buffers: shared hit=128
-> Bitmap Index Scan on orders_store_time_idx (actual rows=120.00
loops=1)
Index Cond: ((placed_at >= '2026-03-0110:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-01 11:00:00+05:30'::timestamp with time zone))
Index Searches: 42
Buffers: shared hit=126
(8 rows)
The index is used although the query does not mention store_id. The data has 40 stores and the scan reports 42 searches: one per store, as in the documentation's skip scan example, plus two that the documentation does not account for. A one-hour window of 120 rows also reports 42 (126 index buffers, three per search), so the count follows the number of stores, not the width of the range. A whole day is 2,880 rows and took 175 buffers, 150 of them index pages, against 8,334 for a sequential scan.
Reversing the columns
Drop the index and build one on (placed_at, store_id), then repeat the first query and a query on the store alone.
sql
DROPINDEX orders_store_time_idx;
sql
CREATEINDEX orders_time_store_idx ON orders (placed_at, store_id);
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, total FROM orders
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
------------------------------------------------------------------------
Index Scan using orders_time_store_idx on orders (actual rows=72.00
loops=1)
Index Cond: ((placed_at >= '2026-03-01 00:00:00+05:30'::timestamp with
time zone) AND (placed_at < '2026-03-02 00:00:00+05:30'::timestamp
with time zone) AND (store_id = 7))
Index Searches: 1
Buffers: shared hit=38
(4 rows)
All three conditions are in the Index Cond, but the day range comes first, so the scan covers the 2,880 entries of that day and tests the store inside the index, as the documentation describes for columns right of a range. It returned the same 72 rows and touched 38 buffers against 28. The plans differ in shape, so read this as an effect of the wanted entries being spread among 2,880, not as a ranking.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, total FROM orders WHERE store_id = 7;
text
QUERY PLAN
-------------------------------------------------
Seq Scan on orders (actual rows=25000.00 loops=1)
Filter: (store_id = 7)
Rows Removed by Filter: 975000
Buffers: shared hit=8334
(4 rows)
A query on the store alone gets no help from this index. The store sits behind ten lakh distinct times, so a skip scan would need a search per time value, and the planner reads the whole table: 8,334 buffers.
Query shape
Index that fits
Why
store = 7, day in a range
(store_id, placed_at)
Equality first, range last: matches are contiguous.
store = 7 ORDER BY placed_at
(store_id, placed_at)
One store's entries come out sorted.
store = 7 alone
store_id first
An unconstrained leading column hurts unless it has few values.
If two columns are both compared with =, either order serves that query, so put first the column that is also used alone. The documentation warns that indexes with more than three columns rarely pay off.
Check yourself
Why is (store_id, placed_at) better than (placed_at, store_id) for store 7 and one day?
With the store first, the matching entries are contiguous, so one search reads only them.
With the day first, the scan covers every entry of the day and tests the store inside the index.
What did Index Searches: 42 show for the skip scan?
About one search per store: with 40 stores it reported 42. The skip scan repeats the search for each value of the leading column, using the condition on the later column each time. The two extra searches are not explained here.
The index is on (placed_at, store_id) and there are ten lakh distinct timestamps. Why did WHERE store_id = 7 read the whole table?
The leading column has too many distinct values for a skip scan to be worth it, so the planner chose a sequential scan.
Part 4 · Covering indexes and index-only scans
Answering from the index alone
A normal index scan finds ctids in the index and then visits the heap for each row to read the other columns. If every column the query needs is already inside the index, the heap visit can be skipped. That plan is an index-only scan, and an index that makes it possible is called a covering index for that query.
Two conditions must hold. First, the query may reference only columns stored in the index. For an index on (store_id, placed_at), a query that also selects status is not covered. Second, the server must be sure that each row is visible to the current transaction, and the index entry does not say that. Visibility is stored in the heap, in every tuple's header.
To avoid the heap visit PostgreSQL keeps a visibility map: one bit per heap page, set when every tuple on that page is visible to all current and future transactions. An index-only scan checks the bit for the page that a candidate entry points to. If the bit is set, the row is returned straight from the index. If it is not set, the scan must visit the heap page after all, and EXPLAIN counts that as a heap fetch. The documentation says an index-only scan is a win only when a significant fraction of the table's pages have their bit set. VACUUM sets the bits, and any change to a page clears its bit.
Adding a column to the key makes the index larger and changes its sort order. If the extra column is only needed in the answer, INCLUDE stores it as a payload that is not part of the search key: CREATE INDEX ... (store_id, placed_at) INCLUDE (status). Only B-tree, GiST and SP-GiST indexes support included columns. GIN cannot support index-only scans at all, because its entries hold only part of the original value.
Before and after VACUUM
The runs below use a copy of orders made for this lesson. Autovacuum is switched off on this one table, so that the state before the first manual vacuum stays steady. On a normal table autovacuum does the work that VACUUM does here. The table starts with a plain two-column index, and the query asks for the day's placed_at and status of store 7.
sql
CREATETABLE orders_cov (LIKE orders) WITH (autovacuum_enabled = false);
INSERTINTO orders_cov SELECT * FROM orders;
CREATEINDEX orders_cov_plain_idx ON orders_cov (store_id, placed_at);
ANALYZE orders_cov;
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT placed_at, status FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders_cov (actual rows=72.00 loops=1)
Recheck Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Blocks: exact=24
Buffers: shared hit=24 read=4
-> Bitmap Index Scan on orders_cov_plain_idx (actual rows=72.00
loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Index Searches: 1
Buffers: shared read=4
(10 rows)
The first run on a new table shows read= as well as hit=; the total is what counts.
status is not in the index, so the plan reads the heap: 24 heap pages and 4 index pages, 28 buffers in all. Now replace the index with one that includes status, and check the size of each.
sql
CREATEINDEX orders_cov_idx ON orders_cov (store_id, placed_at)
INCLUDE (status);
sql
SELECT relname, pg_relation_size(oid) / 8192AS pages FROM pg_class
WHERE relname = 'orders_cov_plain_idx';
The covering index has 6,051 pages against 3,853, because every entry now also stores a status string. The extra size is the price. Now the same query with the covering index, before any vacuum.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT placed_at, status FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders_cov (actual rows=72.00 loops=1)
Recheck Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Blocks: exact=24
Buffers: shared hit=24 read=3
-> Bitmap Index Scan on orders_cov_idx (actual rows=72.00 loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Index Searches: 1
Buffers: shared read=3
(10 rows)
The planner did not choose an index-only scan. It keeps a count of all-visible pages in the table's statistics (relallvisible in pg_class), and for this table that count is zero, so it predicts no benefit and picks a bitmap scan again. The query below reads that count and the size of the visibility map, a separate file of the table: both are zero before the first vacuum. To see the index-only scan itself, turn bitmap scans off for the session. That is for learning only, and the setting is reset afterwards.
sql
SELECT relallvisible, pg_relation_size('orders_cov', 'vm') AS vm_bytes
FROM pg_class WHERE relname = 'orders_cov';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT placed_at, status FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
---------------------------------------------------------------------
Index Only Scan using orders_cov_idx on orders_cov (actual rows=72.00
loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Fetches: 72
Index Searches: 1
Buffers: shared hit=27
(5 rows)
Now there is an Index Only Scan, but Heap Fetches: 72: every one of the 72 rows needed a heap visit, because no page is marked all-visible yet. The scan touched 27 buffers, 3 index pages and 24 heap pages, which is no better than the plain index scan. The bitmap setting goes back to normal and the table is vacuumed.
sql
RESET enable_bitmapscan;
sql
VACUUM orders_cov;
sql
SELECT relallvisible, pg_relation_size('orders_cov', 'vm') AS vm_bytes
FROM pg_class WHERE relname = 'orders_cov';
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT placed_at, status FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
---------------------------------------------------------------------
Index Only Scan using orders_cov_idx on orders_cov (actual rows=72.00
loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=4
(7 rows)
sql
SELECT level FROM bt_metap('orders_cov_idx');
text
level
-----
2
(1 row)
The planner now picks the index-only scan on its own, Heap Fetches is 0, and the whole query reads 4 buffers. The index has level 2, as the query above shows, so a descent reads three index pages, and the fourth buffer is most likely the one page of the visibility map, which the earlier query showed is now 8,192 bytes. The plan does not label the buffer, so this split is an inference. A query that needed 28 buffers needs 4.
When the map goes stale
The benefit lasts only while pages stay unchanged. An UPDATE rewrites a row, which clears the bit for the pages it touches. The statements below change one of the 72 orders and run the query again, without a new vacuum.
sql
SELECT order_id FROM orders_cov WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02'ORDERBY placed_at LIMIT1;
text
order_id
--------
169926
(1 row)
sql
UPDATE orders_cov SET status = 'cancelled'WHERE order_id = (
SELECT order_id FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02'ORDERBY placed_at LIMIT1);
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT placed_at, status FROM orders_cov
WHERE store_id = 7AND placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
---------------------------------------------------------------------
Index Only Scan using orders_cov_idx on orders_cov (actual rows=72.00
loops=1)
Index Cond: ((store_id = 7) AND (placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Heap Fetches: 4
Index Searches: 1
Buffers: shared hit=7
(5 rows)
Heap Fetches is now 4: entries that point into the changed pages must be checked in the heap, and the query reads 7 buffers instead of 4. The scan is still correct, and still cheaper than before the vacuum. Heavy update traffic on a table keeps clearing bits, so an index-only scan on a hot table is only as good as autovacuum is current. Insert-only tables, such as event logs, benefit most.
INCLUDE also behaves differently from a longer key when the index is unique. The documentation says uniqueness applies only to the key columns. The next statements show both versions on the same data. A unique index on order_id with status included refuses a second row with an existing order_id, whatever its status.
sql
CREATE UNIQUE INDEX orders_cov_uniq ON orders_cov (order_id)
INCLUDE (status);
ERROR 23505: duplicate key value violates unique constraint
"orders_cov_uniq"
SQLSTATE 23505 is the unique violation. If status were part of the key instead, the pair (10, 'delivered') and (10, 'placed') would be different keys, and both would be accepted. The query below builds that case on a small table.
sql
CREATETABLE pairs (order_id int, status text);
CREATE UNIQUE INDEX pairs_uniq ON pairs (order_id, status);
INSERTINTO pairs (order_id, status) VALUES (10, 'delivered'), (10,
'placed');
SELECT order_id, status FROM pairs ORDERBY status;
Both rows went in. For a covering index that must stay unique on the real key, use INCLUDE; for a unique rule over several columns, use a composite key.
Check yourself
A plan shows Index Only Scan and Heap Fetches: 72 for 72 rows. What does that tell you?
None of the heap pages the entries point to is marked all-visible, so every row needed a heap visit. The index-only scan saved nothing until a VACUUM sets the bits.
After a VACUUM, one UPDATE changes a row covered by the index. What happens to the next index-only scan?
The update clears the all-visible bit for the page it touched, so the entries pointing into it need heap fetches. Here, 4 fetches and 7 buffers instead of 0 and 4.
When would you use INCLUDE (status) instead of making status a third key column?
When status is only needed in the result, not for searching or sorting, or when the index is unique on the first columns and the extra column must not take part in the uniqueness rule.
Part 5 · Partial and expression indexes
Indexing only some rows
A partial index has a WHERE clause, and only rows that satisfy it get an entry. It is smaller, faster to search and cheaper to maintain, because a write to a row outside the condition does not touch the index. The usual case is a table where the rows you query are a small slice, such as orders still waiting for delivery, or accounts that are not deleted.
The orders table has three statuses. Counting them shows how lopsided the data is.
sql
SELECT status, count(*) AS orders FROM orders GROUPBY status
ORDERBY status;
Only 5,000 of ten lakh orders are placed, and the operations team looks at those all day. Build two indexes on placed_at, one for every row and one for the placed rows only, and compare the sizes.
sql
CREATEINDEX orders_placed_full_idx ON orders (placed_at);
sql
CREATEINDEX orders_placed_open_idx ON orders (placed_at)
WHERE status = 'placed';
sql
SELECT relname, pg_relation_size(oid) / 8192AS pages FROM pg_class
WHERE relname IN ('orders_placed_full_idx', 'orders_placed_open_idx')
ORDERBY relname;
The full index has 2,745 pages and the partial one 16, about one hundred and seventy times smaller. It indexes half a percent of the rows, and it is small enough to stay in memory.
Now the matching rule. PostgreSQL's documentation says a partial index can be used only if the planner can prove that the query's WHERE condition implies the index predicate. The planner has no general theorem prover. It recognises simple inequality implications, and otherwise the predicate must appear in the query as written. The full index is dropped so that only the partial one is left.
sql
DROPINDEX orders_placed_full_idx;
sql
ANALYZE orders;
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, placed_at FROM orders WHERE status = 'placed'AND placed_at >= '2026-12-10';
text
QUERY PLAN
-----------------------------------------------------------------------
Index Scan using orders_placed_open_idx on orders (actual rows=5000.00
loops=1)
Index Cond: (placed_at >= '2026-12-10 00:00:00+05:30'::timestamp with
time zone)
Index Searches: 1
Buffers: shared hit=43 read=15 written=15
(6 rows)
The query repeats status = 'placed', and the planner uses the partial index. The index condition shows only the time range: the status test is already guaranteed by the index. The query read 58 buffers (the written figure counts blocks this query wrote itself and depends on what else was in memory; ignore it here). A query for another status cannot use it.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, placed_at FROM orders WHERE status = 'delivered'AND placed_at >= '2026-12-10';
text
QUERY PLAN
--------------------------------------------------------------------
Seq Scan on orders (actual rows=7017.00 loops=1)
Filter: ((placed_at >= '2026-12-10 00:00:00+05:30'::timestamp with
time zone) AND (status = 'delivered'::text))
Rows Removed by Filter: 992983
Buffers: shared hit=8334
(4 rows)
For delivered the plan reads the whole table, 8,334 buffers, because the index holds no entries for those rows. A partial index serves only queries that contain its condition.
The parameter trap
Matching happens when the query is planned, so a condition whose value is a parameter does not match. The documentation says parameterised query clauses do not work with a partial index. A prepared statement may be planned before the value is known. Forcing a generic plan, one made without the parameter value, shows it.
sql
PREPARE by_status (text) ASSELECT order_id, placed_at FROM orders
WHERE status = $1AND placed_at >= '2026-12-10';
sql
SET plan_cache_mode = force_generic_plan;
sql
EXPLAIN (COSTS OFF) EXECUTE by_status ('placed');
text
QUERY PLAN
--------------------------------------------------------------------
Seq Scan on orders
Filter: ((placed_at >= '2026-12-10 00:00:00+05:30'::timestamp with
time zone) AND (status = $1))
(2 rows)
The plan is a sequential scan. The status is $1, so the planner cannot prove that it equals placed. By default PostgreSQL uses custom plans for the first five executions of a prepared statement, with the parameter value known, and then decides whether a generic plan is good enough. That is why an application can see a partial index work in testing and then stop working in production, once a driver reuses a generic plan. If an application sends the status as a parameter, check the plan the driver really produces, or write the constant into the query.
sql
RESET plan_cache_mode;
Partial indexes also have a maintenance side. If the condition names a fixed set of values, the index must be redesigned when the data changes. The documentation advises against many partial indexes that differ only by a value, such as one per category. One composite index, or partitioning, is usually better, because the planner has to test every partial index against every query.
Indexing a computed value
An expression index stores the result of an expression instead of a plain column. It answers queries that filter on that same expression. The standard example is a case-insensitive lookup. The accounts table below has 2 lakh email addresses, one third of them with a capital letter at the start.
sql
CREATETABLE accounts (account_id int PRIMARYKEY, email text,
deleted_at timestamptz);
INSERTINTO accounts (account_id, email, deleted_at)
SELECT i, CASEWHEN i % 3 = 0THEN'User' ELSE 'user'END || i ||
'@example.com', NULLFROM generate_series(1, 200000) AS g(i);
A search that wraps the column in lower() cannot use a plain index on email. The filtering chapter showed the same effect with a function on a column, where the plan scanned the whole table. Without any index on the expression, this is the plan.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT account_id FROM accounts
WHERE lower(email) = 'user777@example.com';
text
QUERY PLAN
------------------------------------------------------
Seq Scan on accounts (actual rows=1.00 loops=1)
Filter: (lower(email) = 'user777@example.com'::text)
Rows Removed by Filter: 199999
Buffers: shared hit=1470
(6 rows)
1,470 buffers, the whole table. Now index the expression itself.
sql
CREATEINDEX accounts_lower_email_idx ON accounts (lower(email));
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT account_id FROM accounts
WHERE lower(email) = 'user777@example.com';
text
QUERY PLAN
---------------------------------------------------------------------
Bitmap Heap Scan on accounts (actual rows=1.00 loops=1)
Recheck Cond: (lower(email) = 'user777@example.com'::text)
Heap Blocks: exact=1
Buffers: shared hit=1 read=3
-> Bitmap Index Scan on accounts_lower_email_idx (actual rows=1.00
loops=1)
Index Cond: (lower(email) = 'user777@example.com'::text)
Index Searches: 1
Buffers: shared read=3
(10 rows)
The bitmap scan finds the row in 4 buffers: 3 index pages and 1 heap page, with Index Cond: (lower(email) = ...). The index stores the lowered value, so the search does not compute lower() again. The cost moves to writes. The documentation says index expressions are relatively expensive to maintain, because the expression is computed for every row insertion and every non-HOT update, an update that changes the row's indexed entries.
The query must use the same expression. These two queries do not match the index.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT account_id FROM accounts WHERE email = 'User777@example.com';
text
QUERY PLAN
-----------------------------------------------
Seq Scan on accounts (actual rows=1.00 loops=1)
Filter: (email = 'User777@example.com'::text)
Rows Removed by Filter: 199999
Buffers: shared hit=1470
(6 rows)
sql
EXPLAIN (COSTS OFF)
SELECT account_id FROM accounts
WHERE upper(email) = 'USER777@EXAMPLE.COM';
text
QUERY PLAN
------------------------------------------------------
Seq Scan on accounts
Filter: (upper(email) = 'USER777@EXAMPLE.COM'::text)
(2 rows)
Comparing the plain column with a mixed-case string cannot use an index on lower(email), since the entries are lowered. upper(email) is a different expression and has no index. Both plans read the whole table. Pick one canonical form for a lookup, and use it in every query that should hit the index.
Unique rules on part of a table
A partial index can be unique, which enforces a rule on only the rows the condition selects. A common case is soft deletion: a row marked deleted should not block a new row with the same email. Combine the two ideas: a unique index on lower(email) for the rows where deleted_at IS NULL.
sql
CREATE UNIQUE INDEX accounts_live_email_idx ON accounts (lower(email))
WHERE deleted_at ISNULL;
ERROR 23505: duplicate key value violates unique constraint
"accounts_live_email_idx"
The insert fails with SQLSTATE 23505, even though the new address differs in case, because the index stores the lowered value. Mark the old account as deleted, and the same address can be registered again.
sql
UPDATE accounts SET deleted_at = now() WHERE account_id = 5;
Account 5 is deleted, account 200001 holds the address, and two accounts with NULL email were inserted without complaint. A unique index treats each NULL as different from every other value, so any number of rows may have one. That is the standard behaviour, and it matters when the column is optional: if the column should allow only one empty value, the CREATE INDEX page documents a NULLS NOT DISTINCT option for that, which this lesson does not run.
Index
Use it when
Cost to watch
Partial, WHERE status = 'placed'
queries always repeat the condition and the slice is small
does not serve other values or parameterised conditions
Expression, lower(email)
queries filter on that exact expression
computed on every insert and on updates of the row
Unique partial, WHERE deleted_at IS NULL
a rule must hold only for live rows
queries need the same condition to use it
Check yourself
The partial index covers status = 'placed'. Why did the query for delivered scan the whole table?
The index has no entries for rows that are not placed, and the planner can use it only when the query implies its condition.
A prepared statement with status = $1 ignored the partial index in a generic plan. Why?
A generic plan is made before the value is known, so the planner cannot prove that $1 equals placed. Matching happens at planning time.
An index exists on lower(email). Which of these can use it: WHERE lower(email) = 'a@example.com' or WHERE email = 'a@example.com'?
Only the first. The index stores lowered values, and the planner matches the expression, not the column.
Part 6 · Other index types
Six access methods
B-tree is the default and covers equality, ranges and sorting. PostgreSQL has five other built-in index access methods, each for data or questions that a B-tree answers badly. An index can serve a query only if its operator class contains the operator the query uses. The lesson runs hash, BRIN and GIN, and ends with a GiST example.
Method
What it is built for
Typical operators
B-tree
Equality, ranges and sorted output
=, <, <=, >, >=, BETWEEN, IN
Hash
Simple equality only, from a 32-bit hash of the value
=
GiST
Many strategies: geometry, ranges, nearest-neighbour search, exclusion constraints
Values with many parts: arrays, jsonb, text search
@>, ?, @@
BRIN
Block-range summaries, for huge tables whose column follows the physical order
=, <, >
The runs use the orders table from the earlier lessons: a B-tree and a hash index on customer_id, and a BRIN index on each of placed_at and customer_id. Sizes are in 8 KB pages.
sql
CREATEINDEX orders_cust_btree ON orders (customer_id);
sql
CREATEINDEX orders_cust_hash ON orders USING hash (customer_id);
sql
CREATEINDEX orders_placed_brin ON orders USING brin (placed_at);
sql
CREATEINDEX orders_cust_brin ON orders USING brin (customer_id);
sql
ANALYZE orders;
sql
SELECT c.relname, am.amname AS method,
pg_relation_size(c.oid) / 8192AS pages,
pg_size_pretty(pg_relation_size(c.oid)) AS size
FROM pg_class c JOIN pg_am am ON am.oid = c.relam
WHERE c.relname IN ('orders_cust_btree', 'orders_cust_hash',
'orders_placed_brin', 'orders_cust_brin')
ORDERBY pages DESC;
The BRIN indexes take 3 pages, 24 kB, for ten lakh rows. The B-tree on customer_id takes 950 pages and the hash index 4,028. Every customer has about 20 orders, and a B-tree stores a repeated key once with its list of ctids (deduplication, on by default). The hash index page of the documentation describes no such merging. Do not expect the same ratio on a column of unique values.
Hash: equality only
A hash index stores a 32-bit hash code of the key and the ctid, and answers only =. The documentation lists its limits: one column only, and no uniqueness checking. It also says that hash indexes are fully crash recoverable.
Bitmap scans are off for this run, and the B-tree on customer_id is dropped, so only the hash index can serve the query.
sql
SET enable_bitmapscan = off;
sql
DROPINDEX orders_cust_btree;
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id FROM orders WHERE customer_id = 4242;
text
QUERY PLAN
-----------------------------------------------------------------------
Index Scan using orders_cust_hash on orders (actual rows=20.00 loops=1)
Index Cond: (customer_id = 4242)
Index Searches: 1
Buffers: shared hit=21
(6 rows)
Twenty rows came back for 21 buffers. A hash index finds an equal key, and a B-tree does that too, besides ranges and sorting.
sql
EXPLAIN (COSTS OFF)
SELECT order_id FROM orders WHERE customer_id BETWEEN4242AND4250;
text
QUERY PLAN
-----------------------------------------------------------
Seq Scan on orders
Filter: ((customer_id >= 4242) AND (customer_id <= 4250))
(2 rows)
A range on the same column gives a sequential scan: the hash of 4242 says nothing about the hash of 4243. If a column is ever used in a range or an ORDER BY, use a B-tree. For a column only ever compared with =, measure before preferring a hash index.
BRIN: tiny indexes for ordered data
A BRIN (block range index) does not index rows. It splits the table into ranges of consecutive pages, 128 pages by default, and stores a summary of each, such as the minimum and maximum value. A query for a value outside a range's summary skips all 128 pages. The index is lossy: when the summary matches, every row of the range is returned and the executor rechecks each one.
That works only when the column follows the physical order of the table. placed_at does, since orders were inserted in time order, and customer_id does not. The statistics view reports the correlation between a column and the physical order: 1 means perfectly ordered.
sql
SELECT attname, correlation FROM pg_stats WHERE tablename = 'orders'AND attname IN ('placed_at', 'customer_id') ORDERBY attname;
customer_id is from a sample taken by ANALYZE, so its value is close to zero. Every figure that ANALYZE estimates from a sample changes a little between runs, here and in the chapters that follow.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id FROM orders WHERE placed_at >= '2026-03-01'AND placed_at < '2026-03-02';
text
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on orders (actual rows=2880.00 loops=1)
Recheck Cond: ((placed_at >= '2026-03-01 00:00:00+05:30'::timestamp
with time zone) AND (placed_at < '2026-03-0200:00:00+05:30'::timestamp with time zone))
Rows Removed by Index Recheck: 12480
Heap Blocks: lossy=128
Buffers: shared hit=133
-> Bitmap Index Scan on orders_placed_brin (actual rows=1280.00
loops=1)
Index Cond: ((placed_at >= '2026-03-0100:00:00+05:30'::timestamp with time zone) AND (placed_at <
'2026-03-02 00:00:00+05:30'::timestamp with time zone))
Index Searches: 1
Buffers: shared hit=5
(11 rows)
One day of orders is 2,880 rows, about 24 pages. The index scan returned the single 128-page range that holds them (Heap Blocks: lossy=128), and Rows Removed by Index Recheck: 12480 counts the rows of that range that did not match. The query read 133 buffers, 5 of them from a 24 kB index, against 8,334 for a table scan. A B-tree on the same column was 2,745 pages, about nine hundred times larger. BRIN trades extra heap pages for a tiny index, which suits append-only data such as logs and event tables.
On a column with no physical order, a BRIN index cannot skip anything. The query below asks for nine customer numbers.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id FROM orders WHERE customer_id BETWEEN4242AND4250;
text
QUERY PLAN
-----------------------------------------------------------
Seq Scan on orders (actual rows=180.00 loops=1)
Filter: ((customer_id >= 4242) AND (customer_id <= 4250))
Rows Removed by Filter: 999820
Buffers: shared hit=8334
(6 rows)
The planner ignores the BRIN index on customer_id and reads the table: every range holds customers from the whole id range, so every summary overlaps the question. Check the correlation before you create a BRIN index.
GIN: indexing the parts of a value
A GIN (generalised inverted index) stores each component of a value as a key with the list of rows that contain it, like the index at the back of a book. It suits arrays, jsonb and text search vectors, where the question is "which rows contain this element". The documentation says that inserting or updating one row can cause many index inserts, one per extracted key, so GIN suits read-heavy data.
The table below holds 2 lakh product records with a jsonb column. One in a thousand has the tag festival.
sql
CREATETABLE catalog_docs (doc_id int PRIMARYKEY, attrs jsonb NOTNULL);
INSERTINTO catalog_docs (doc_id, attrs)
SELECT i, jsonb_build_object(
'pack', (ARRAY['250g','500g','1kg'])[i % 3 + 1],
'organic', i % 10 = 0,
'tags', CASEWHEN i % 1000 = 0THEN jsonb_build_array('festival', 'gift')
ELSE jsonb_build_array('staple') END)
FROM generate_series(1, 200000) AS g(i);
The containment operator @> asks whether a document contains a given fragment. Without an index, the server must read and open every document.
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT doc_id FROM catalog_docs WHERE attrs @> '{"tags": ["festival"]}';
text
QUERY PLAN
-----------------------------------------------------
Seq Scan on catalog_docs (actual rows=200.00 loops=1)
Filter: (attrs @> '{"tags": ["festival"]}'::jsonb)
Rows Removed by Filter: 199800
Buffers: shared hit=2470
(6 rows)
sql
CREATEINDEX catalog_docs_gin ON catalog_docs USING gin (attrs);
sql
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT doc_id FROM catalog_docs WHERE attrs @> '{"tags": ["festival"]}';
text
QUERY PLAN
------------------------------------------------------------------------
Bitmap Heap Scan on catalog_docs (actual rows=200.00 loops=1)
Recheck Cond: (attrs @> '{"tags": ["festival"]}'::jsonb)
Heap Blocks: exact=200
Buffers: shared hit=257
-> Bitmap Index Scan on catalog_docs_gin (actual rows=200.00 loops=1)
Index Cond: (attrs @> '{"tags": ["festival"]}'::jsonb)
Index Searches: 1
Buffers: shared hit=57
(10 rows)
The sequential scan read 2,470 buffers to find 200 documents. With the GIN index, 57 were index pages and 200 heap pages. The index takes 173 pages for a table of 2,470.
The default jsonb operator class, jsonb_ops, supports @>, ?, ?|, ?&, @? and @@. jsonb_path_ops supports only @>, @? and @@ and, according to the documentation, performs better for those. An index serves an operator only when it is applied to the indexed column. The next query applies ? and ->> to expressions inside the document, so neither matches the index on attrs.
sql
EXPLAIN (COSTS OFF)
SELECT doc_id FROM catalog_docs WHERE attrs ->> 'pack' = '1kg'AND attrs -> 'tags' ? 'festival';
text
QUERY PLAN
-----------------------------------------------------------------------
Seq Scan on catalog_docs
Filter: (((attrs -> 'tags'::text) ? 'festival'::text) AND ((attrs ->>
'pack'::text) = '1kg'::text))
(2 rows)
The plan is a sequential scan. Writing the same question with containment, attrs @> '{"tags": ["festival"]}', uses the index.
GiST and exclusion constraints
A GiST index is a framework. Its best-known use in application code is an exclusion constraint: no two rows may conflict under a set of operators. A booking table can say that no two bookings for one hall overlap in time, which a unique constraint cannot express because it tests equality. The btree_gist extension, shipped with the server, lets one constraint mix = on a text column with && (overlap) on a range.
sql
CREATE EXTENSION IF NOTEXISTS btree_gist;
CREATETABLE hall_bookings (
hall text NOTNULL,
during tstzrange NOTNULL,
EXCLUDE USING gist (hall WITH =, during WITH &&)
);
INSERTINTO hall_bookings (hall, during)
VALUES ('Hall A', tstzrange('2026-12-01 10:00+05:30',
'2026-12-01 12:00+05:30'));
The statement creates the table and adds a first booking, 10:00 to 12:00 in Hall A. A second booking from 11:00 to 13:00 in the same hall overlaps.
ERROR 23P01: conflicting key value violates exclusion constraint
"hall_bookings_hall_during_excl"
SQLSTATE 23P01 is the exclusion violation. Ranges in PostgreSQL are half-open by default, [start, end), so a booking that starts exactly when another ends is allowed, and so is the same time in another hall.
SELECT hall, during::text AS during
FROM hall_bookings
ORDERBY hall, during;
text
hall | during
-------+----------------------------------------------------------
Hall A | ["2026-12-01 10:00:00+05:30","2026-12-01 12:00:00+05:30")
Hall A | ["2026-12-01 12:00:00+05:30","2026-12-01 13:00:00+05:30")
Hall B | ["2026-12-01 11:00:00+05:30","2026-12-01 13:00:00+05:30")
(3 rows)
Three bookings are stored. The database enforces the rule for every writer, so it does not depend on each application remembering to check for a clash first.
Check yourself
Why did a hash index on customer_id give a sequential scan for BETWEEN 4242 AND 4250?
A hash index supports only =. The hash of one key says nothing about neighbouring keys, so it cannot answer a range.
A BRIN index on customer_id was ignored, while one on placed_at was used. What decides it?
Correlation with the physical order. placed_at is close to 1, so each block range holds a narrow slice of values. customer_id is close to 0, so every range overlaps the query.
Why did the query attrs -> 'tags' ? 'festival' not use the GIN index on attrs?
The operator was applied to an expression inside the document, not to the indexed column. The index matches attrs by operator class: it only answers operators it supports on that column.
Part 7 · What indexes cost
Every index is paid for on every write
An index speeds up reads and slows down writes. Each INSERT adds an entry to every index on the table. A DELETE leaves its entries for vacuum to clean up, and an UPDATE that changes an indexed column adds new ones. Indexes also take disk space, memory in shared buffers and vacuum time.
The script below inserts 2 lakh rows into a table with 0, 1, 3 and 5 indexes, three times each, and prints the milliseconds per insert and the total size of the indexes. It runs a CHECKPOINT before each timed insert so that earlier work does not leak into the timing.
ts
import pg from'pg'const db = new pg.Client({ host: '127.0.0.1', port: 56320,
user: 'postgres', database: 'idx' })
await db.connect()
const cols = ['customer_id', 'store_id, placed_at', 'placed_at',
'status, total', 'total']
const load = `INSERT INTO t_ins (order_id, customer_id, store_id,
placed_at, status, total)
SELECT i, i % 50000 + 1, i % 40 + 1, now(), 'delivered', i % 900FROM generate_series(1, 200000) AS g(i)`
for (const n of [0, 1, 3, 5]) {
const ms: number[] = []
for (let run = 0; run < 3; run++) {
await db.query('DROP TABLE IF EXISTS t_ins')
await db.query(`CREATETABLE t_ins (order_id int, customer_id int,
store_id int, placed_at timestamptz, status text, total numeric)`)
for (const c of cols.slice(0, n))
await db.query(`CREATE INDEX ON t_ins (${c})`)
await db.query('CHECKPOINT')
const t0 = performance.now()
await db.query(load)
ms.push(Math.round(performance.now() - t0))
}
const r = await db.query(`SELECT round(coalesce(sum(
pg_relation_size(indexrelid)), 0) / 1048576.0, 1)::text AS mb
FROM pg_index WHERE indrelid = 't_ins'::regclass`)
console.log(`${n} | ${ms.join(' | ')} | ${r.rows[0].mb}`)
}
await db.end()
text
indexes | run 1 ms | run 2 ms | run 3 ms | index MB
0 | 483 | 470 | 407 | 0.01 | 860 | 691 | 753 | 3.23 | 1438 | 1473 | 1508 | 5.85 | 2713 | 3939 | 3542 | 19.9
Timings are from one session on this machine and vary from run to run.
The first row is the table with no index. The table below puts three sessions of this script on a quiet machine next to the first run of it, made while other work was running. Each cell is the fastest and slowest of three inserts, in milliseconds.
Indexes
Session 1 (shown)
Session 2
Session 3
Busy session
0
407-483
374-497
290-415
1,118-1,217
1
691-860
751-794
598-765
995-1,815
3
1,438-1,508
1,576-1,717
1,041-1,320
1,321-2,073
5
2,713-3,939
2,996-3,936
2,833-7,245
2,839-3,814
0
Session 1 (shown)407-483
Session 2374-497
Session 3290-415
Busy session1,118-1,217
1
Session 1 (shown)691-860
Session 2751-794
Session 3598-765
Busy session995-1,815
3
Session 1 (shown)1,438-1,508
Session 21,576-1,717
Session 31,041-1,320
Busy session1,321-2,073
5
Session 1 (shown)2,713-3,939
Session 22,996-3,936
Session 32,833-7,245
Busy session2,839-3,814
In each quiet session the groups were ordered 0, 1, 3, 5 with no overlap, but in the busy session the first three overlap, and the same code took between 290 and 1,217 ms with no index at all. Absolute figures do not travel between sessions, and groups whose ranges overlap cannot be ranked. What held in all four sessions: five indexes were the slowest, and they added about 20 MB for 2 lakh rows.
The cost is paid again on every row the application writes, for the life of the table. That is the reason to add an index for a query that matters and to drop one that does not.
Finding indexes that nobody uses
pg_stat_user_indexes has one row per index, with idx_scan, the number of scans started on it since statistics were last reset. This query lists the indexes of orders, least used first, with their sizes: the indexes from the earlier lessons.
sql
SELECT indexrelname AS index_name, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'orders'ORDERBY idx_scan, indexrelname;
orders_cust_brin, the BRIN index on the column with no physical order that the planner ignored in the previous lesson, has 0 scans. It is only 24 kB, but a large index with zero scans is a candidate for dropping, and every write still maintains it.
Read these counters carefully. They count from the last statistics reset, and they are kept per server: an index nobody uses on the primary may serve queries on a replica, and a query that runs once a quarter may not have run yet. An index that enforces a primary key or unique constraint does its job on writes even when it is never scanned. Drop an index only after watching it over a full business cycle, and keep its definition so that you can recreate it.
Foreign keys do not index themselves
A foreign key guarantees that a child row's value exists in the parent table. The parent side has an index, because the referenced column must be a primary key or have a unique index. The child side is not indexed automatically. The documentation says that a DELETE of a parent row, or an update of its key, requires a scan of the referencing table, so it is often a good idea to index the referencing columns.
The tables below have 50,001 customers and 5 lakh orders that reference them. Customer 50001 has no orders. The listing shows the indexes that exist.
sql
CREATETABLE fk_customers (customer_id int PRIMARYKEY, name text NOTNULL);
INSERTINTO fk_customers (customer_id, name) SELECT i, 'Customer ' || i
FROM generate_series(1, 50001) AS g(i);
CREATETABLE fk_orders (
order_id int PRIMARYKEY,
customer_id int NOTNULLREFERENCES fk_customers (customer_id),
total numeric(10,2) NOTNULL
);
INSERTINTO fk_orders (order_id, customer_id, total)
SELECT i, i % 50000 + 1, 100 + i % 900FROM generate_series(1, 500000)
AS g(i);
sql
SELECT tablename, indexname FROM pg_indexes
WHERE tablename IN ('fk_customers', 'fk_orders')
ORDERBY tablename, indexname;
Only the two primary keys exist. Deleting a customer must check that no order points to it. The statement below runs between BEGIN and ROLLBACK, so the data is unchanged, and EXPLAIN ANALYZE prints the time of the internal foreign key trigger that does the check. Without the wrapper the delete would really happen.
QUERY PLAN
----------------------------------------------------------------------
Delete on fk_customers (actual time=0.025..0.025 rows=0.00 loops=1)
-> Index Scan using fk_customers_pkey on fk_customers (actual
time=0.007..0.008 rows=1.00 loops=1)
Index Cond: (customer_id = 50001)
Index Searches: 1
Trigger for constraint fk_orders_customer_id_fkey: time=20.910 calls=1
(5 rows)
Timings are from one run on this machine; they vary.
The same wrapped statement again.
text
QUERY PLAN
----------------------------------------------------------------------
Delete on fk_customers (actual time=0.031..0.031 rows=0.00 loops=1)
-> Index Scan using fk_customers_pkey on fk_customers (actual
time=0.017..0.018 rows=1.00 loops=1)
Index Cond: (customer_id = 50001)
Index Searches: 1
Trigger for constraint fk_orders_customer_id_fkey: time=28.482 calls=1
(5 rows)
The delete itself takes a few hundredths of a millisecond. The trigger takes between 21 and 28 milliseconds in the two runs, because it scans all 5 lakh rows of fk_orders to look for a referencing row. Now index the referencing column and repeat.
sql
CREATEINDEX fk_orders_customer_idx ON fk_orders (customer_id);
The wrapped delete, run twice more.
text
QUERY PLAN
---------------------------------------------------------------------
Delete on fk_customers (actual time=0.038..0.038 rows=0.00 loops=1)
-> Index Scan using fk_customers_pkey on fk_customers (actual
time=0.020..0.021 rows=1.00 loops=1)
Index Cond: (customer_id = 50001)
Index Searches: 1
Trigger for constraint fk_orders_customer_id_fkey: time=0.727 calls=1
(5 rows)
text
QUERY PLAN
---------------------------------------------------------------------
Delete on fk_customers (actual time=0.019..0.019 rows=0.00 loops=1)
-> Index Scan using fk_customers_pkey on fk_customers (actual
time=0.009..0.010 rows=1.00 loops=1)
Index Cond: (customer_id = 50001)
Index Searches: 1
Trigger for constraint fk_orders_customer_id_fkey: time=0.070 calls=1
(5 rows)
The trigger now takes a fraction of a millisecond. One delete does not matter much; the cost matters when a job deletes many customers, since each parent row triggers one scan of the child table. The same index serves ordinary queries such as "all orders of this customer".
Building indexes on a live table
A plain CREATE INDEX locks the table against writes until it finishes; the documentation says other transactions can still read, but inserts, updates and deletes block. CREATE INDEX CONCURRENTLY builds the index without locks that block writes. It pays with two scans of the table and with waiting for existing transactions to finish.
It has two restrictions that show up as errors. First, it cannot run inside a transaction block.
sql
BEGIN;
CREATEINDEX CONCURRENTLY fk_orders_total_idx ON fk_orders (total);
ROLLBACK;
text
ERROR 25001: CREATE INDEX CONCURRENTLY cannot run inside a transaction
block
SQLSTATE 25001 means the statement was issued inside a transaction. Migration tools that wrap every migration in a transaction need an option to run this one outside. Outside a transaction block, the statement succeeds.
sql
CREATEINDEX CONCURRENTLY fk_orders_total_idx ON fk_orders (total);
Second, if the build fails, it leaves a broken index behind. The next statement asks for a unique index on a column that has duplicates, since each customer has ten orders in this table, and then lists the indexes with their validity.
sql
CREATE UNIQUE INDEX CONCURRENTLY fk_orders_customer_uniq
ON fk_orders (customer_id);
text
ERROR 23505: could not create unique index "fk_orders_customer_uniq"
sql
SELECT c.relname, i.indisvalid
FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE i.indrelid = 'fk_orders'::regclass
ORDERBY c.relname;
The unique build failed with 23505, but the index fk_orders_customer_uniq is still in the catalogue with indisvalid = false. The planner ignores it, but the documentation notes that it still consumes update overhead, so every write maintains an index that nothing can use. The recommended recovery is to drop it and try again, or rebuild it with REINDEX INDEX CONCURRENTLY.
sql
DROPINDEX fk_orders_customer_uniq;
Cost
Where it shows
What to do
Write time
Every insert, and updates that touch indexed columns
Index for queries that matter; drop the rest
Disk and memory
Index size, shared buffers, backups
Partial indexes, INCLUDE only when needed, BRIN for ordered data
Unused indexes
pg_stat_user_indexes.idx_scan of 0
Watch over a full business cycle, then drop
Missing foreign key index
Slow deletes and updates on the parent table
Index the referencing column
Locks during build
Writes block during a plain CREATE INDEX
CREATE INDEX CONCURRENTLY, outside a transaction
Check yourself
A table has five indexes and writes are slow. How do you decide which index to drop?
Look at idx_scan in pg_stat_user_indexes over a full business cycle. An index that is never scanned and enforces no constraint is a candidate.
Check replicas too, since the counters are per server.
Deleting a customer spends about 25 ms in the foreign key check, in a table of 5 lakh orders. The foreign key column has no index. What is the fix and why does it work?
Create an index on the referencing column. The foreign key trigger then finds referencing rows by an index search instead of scanning the whole child table.
CREATE INDEX CONCURRENTLY fails with SQLSTATE 25001 in a migration. What is wrong?
The statement cannot run inside a transaction block, and the migration tool wrapped it in one. Run it outside a transaction.