SQL Indexes: How They Work and When They Help
How database indexes work and how to use them: B-trees, reading EXPLAIN to see whether an index is used, composite index column order, why functions and leading wildcards defeat indexes, expression, partial and covering indexes, selectivity, the cost of indexes, full-text search and trigram indexes.
kvi5hnuCode Sprout team member14 min readOn this page
Without an index, the only way to find the rows that match a condition is to read every row in the table and test each one. That's fine for a few thousand rows and hopeless for a few hundred million. An index is a separate, sorted structure that lets the database jump straight to the matching rows, the way the index at the back of a manual takes you to the right page without reading every page.
Indexes are the single most important tool for query performance, and the most misunderstood. This article explains how they work, how to tell whether a query uses one, which queries can and can't use them, the kinds of index worth knowing, and what they cost. Article 67 covers reading query plans in depth.
The examples use a table of 200,000 generated orders, from 20,000 customers, with 90% shipped, 9% pending and 1% cancelled:
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, email TEXT NOT NULL,
placed_on DATE NOT NULL, status TEXT NOT NULL, amount NUMERIC(10, 2) NOT NULL
);
How a B-tree index works
The default index type in every major database is the B-tree (balanced tree):

- The leaf pages hold every indexed value in sorted order, each with a pointer to its row in the table.
- Above them, branch pages and a single root page hold separator keys that say which page to go to next.
- To find
customer_id = 4242, the database reads the root, one branch and one leaf: three or four page reads, even for millions of rows, because each level multiplies the number of pages it covers by several hundred. - The leaves are linked to their neighbours, so once the first match is found, a range (
BETWEEN,<,>) or a sorted result can be read by walking along the leaves.
So a B-tree helps with equality (=, IN), ranges, ORDER BY on the indexed columns, MIN and MAX, prefix LIKE 'abc%', and joins on the indexed column. Primary keys and unique constraints create B-tree indexes automatically (article 52). Foreign keys don't, in PostgreSQL.
Seeing whether an index is used
-- Keep plans simple and repeatable: no parallel workers
SET max_parallel_workers_per_gather = 0;
-- 200,000 orders with deterministic, evenly spread data
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
email TEXT NOT NULL,
placed_on DATE NOT NULL,
status TEXT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO big_orders
SELECT g,
(g * 7919) % 20000 + 1,
'Customer' || ((g * 7919) % 20000 + 1) || '@Example.com',
DATE '2024-01-01' + (g % 1000),
CASE WHEN g % 100 = 0 THEN 'cancelled' WHEN g % 10 = 0 THEN 'pending' ELSE 'shipped' END,
(g % 500) + 0.99
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- Without an index, finding one customer's orders reads the whole table
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, amount FROM big_orders WHERE customer_id = 4242;
-- With an index, the database goes straight to the matching rows
CREATE INDEX big_orders_customer_ix ON big_orders (customer_id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT order_id, amount FROM big_orders WHERE customer_id = 4242;
QUERY PLAN
-------------------------------------------------
Seq Scan on big_orders (actual rows=10 loops=1)
Filter: (customer_id = 4242)
Rows Removed by Filter: 199990
(3 rows)
QUERY PLAN
----------------------------------------------------------------------------
Bitmap Heap Scan on big_orders (actual rows=10 loops=1)
Recheck Cond: (customer_id = 4242)
Heap Blocks: exact=10
-> Bitmap Index Scan on big_orders_customer_ix (actual rows=10 loops=1)
Index Cond: (customer_id = 4242)
(5 rows)
EXPLAIN shows the plan the database chose for a query, and EXPLAIN ANALYZE also runs it and reports what happened. (The options here hide the timings and cost estimates, which vary from run to run.)
- Without an index, the plan is a Seq Scan (sequential scan): every row is read, and the filter removes 199,990 rows to find 10.
- After
CREATE INDEX big_orders_customer_ix ON big_orders (customer_id), the plan uses the index. A Bitmap Index Scan finds the 10 matching entries, and a Bitmap Heap Scan fetches just the table pages they point to: 10 pages, instead of the whole table.
Other plan nodes you'll see are Index Scan, which follows the index entries one by one in index order, and Index Only Scan, which answers the query from the index alone, without visiting the table.
CREATE INDEX name ON table (columns) is the same in almost every database. On a busy table, CREATE INDEX CONCURRENTLY (PostgreSQL) builds the index without blocking writes, at the cost of taking longer. SQL Server's ONLINE = ON and MySQL's online DDL are similar.
Composite indexes and column order
An index on several columns sorts by the first column, then by the second within equal first values, like a phone book sorted by surname, then first name:
-- Keep plans simple and repeatable: no parallel workers
SET max_parallel_workers_per_gather = 0;
-- 200,000 orders with deterministic, evenly spread data
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
email TEXT NOT NULL,
placed_on DATE NOT NULL,
status TEXT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO big_orders
SELECT g,
(g * 7919) % 20000 + 1,
'Customer' || ((g * 7919) % 20000 + 1) || '@Example.com',
DATE '2024-01-01' + (g % 1000),
CASE WHEN g % 100 = 0 THEN 'cancelled' WHEN g % 10 = 0 THEN 'pending' ELSE 'shipped' END,
(g % 500) + 0.99
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- A composite index serves queries on its leading column(s)
CREATE INDEX big_orders_cust_date_ix ON big_orders (customer_id, placed_on);
-- Equality on the first column, range on the second, sorted by the second: all from the index
EXPLAIN (COSTS OFF)
SELECT order_id, placed_on FROM big_orders
WHERE customer_id = 4242 AND placed_on >= DATE '2025-01-01'
ORDER BY placed_on;
-- Only the second column: there's no single range to read, so at best the whole index is scanned
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE placed_on = DATE '2025-06-01';
QUERY PLAN
----------------------------------------------------------------------------------------
Sort
Sort Key: placed_on
-> Bitmap Heap Scan on big_orders
Recheck Cond: ((customer_id = 4242) AND (placed_on >= '2025-01-01'::date))
-> Bitmap Index Scan on big_orders_cust_date_ix
Index Cond: ((customer_id = 4242) AND (placed_on >= '2025-01-01'::date))
(6 rows)
QUERY PLAN
------------------------------------------------------------
Aggregate
-> Bitmap Heap Scan on big_orders
Recheck Cond: (placed_on = '2025-06-01'::date)
-> Bitmap Index Scan on big_orders_cust_date_ix
Index Cond: (placed_on = '2025-06-01'::date)
(5 rows)
- The first query has equality on
customer_idand a range onplaced_on. Both conditions are Index Conds: the database goes straight to customer 4242's entries and reads only those from 2025 onwards. With just a few matching rows, the planner fetched them with a bitmap and sorted them, which is cheap. With more rows, it would read the index in order and skip the sort. - The second query filters only on
placed_on, the second column. The index's entries for one date are scattered across every customer's section, so there's no single range to read. PostgreSQL still uses the index here, but it has to scan all of it, which it judged cheaper than scanning the larger table. That's the best case: many databases, and PostgreSQL on other data, would scan the table instead.
The rule, often called the leftmost prefix rule: a composite index on (a, b, c) helps conditions on a, on a and b, or on a, b and c, but not efficiently on b or c alone. When designing one:
- Put columns tested with equality first, and the column tested with a range or used for sorting after them.
- Among equality columns, order by which combinations queries use. An index on
(customer_id, placed_on)also serves queries oncustomer_idalone, so a separate index oncustomer_idbecomes redundant.
PostgreSQL 18 added skip scan for B-trees, which makes conditions on a later column much cheaper when the leading column has few distinct values. Oracle and MySQL 8 have similar skip scans.
What stops an index being used
-- Keep plans simple and repeatable: no parallel workers
SET max_parallel_workers_per_gather = 0;
-- 200,000 orders with deterministic, evenly spread data
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
email TEXT NOT NULL,
placed_on DATE NOT NULL,
status TEXT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO big_orders
SELECT g,
(g * 7919) % 20000 + 1,
'Customer' || ((g * 7919) % 20000 + 1) || '@Example.com',
DATE '2024-01-01' + (g % 1000),
CASE WHEN g % 100 = 0 THEN 'cancelled' WHEN g % 10 = 0 THEN 'pending' ELSE 'shipped' END,
(g % 500) + 0.99
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- A function applied to the column hides it from an ordinary index
CREATE INDEX big_orders_email_ix ON big_orders (email);
EXPLAIN (COSTS OFF)
SELECT order_id FROM big_orders WHERE lower(email) = 'customer4242@example.com';
-- An expression index stores the function's result, so the same expression can use it
CREATE INDEX big_orders_email_lower_ix ON big_orders (lower(email));
ANALYZE big_orders;
EXPLAIN (COSTS OFF)
SELECT order_id FROM big_orders WHERE lower(email) = 'customer4242@example.com';
-- A prefix search can use a B-tree index; a leading wildcard can't
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE email LIKE 'Customer4242@%';
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE email LIKE '%4242@%';
QUERY PLAN
-------------------------------------------------------------
Seq Scan on big_orders
Filter: (lower(email) = 'customer4242@example.com'::text)
(2 rows)
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: (lower(email) = 'customer4242@example.com'::text)
-> Bitmap Index Scan on big_orders_email_lower_ix
Index Cond: (lower(email) = 'customer4242@example.com'::text)
(4 rows)
QUERY PLAN
--------------------------------------------------------------------------------------------
Aggregate
-> Index Only Scan using big_orders_email_ix on big_orders
Index Cond: ((email >= 'Customer4242@'::text) AND (email < 'Customer4242A'::text))
Filter: (email ~~ 'Customer4242@%'::text)
(4 rows)
QUERY PLAN
--------------------------------------------
Aggregate
-> Seq Scan on big_orders
Filter: (email ~~ '%4242@%'::text)
(3 rows)
An index stores the column's values. A condition can use it only if it compares the column itself with something the database can look up:
- A function on the column hides it. The index on
emailstores'Customer4242@Example.com', notlower(email), soWHERE lower(email) = '...'scans the table. The same applies toEXTRACT(YEAR FROM placed_on) = 2025,amount * 1.2 > 100,CAST(customer_id AS TEXT) = '42'and implicit type conversions. Rewrite the condition to leave the column bare where possible, for exampleplaced_on >= DATE '2025-01-01' AND placed_on < DATE '2026-01-01'(article 40). - An expression index solves it when the function is needed:
CREATE INDEX ... ON big_orders (lower(email))stores the lower-case values, and a query using exactly that expression uses the index. This is the standard way to support case-insensitive lookups. LIKEwith a fixed prefix can use a B-tree:LIKE 'Customer4242@%'becomes a range from'Customer4242@'up to'Customer4242A', and here the query is answered by an Index Only Scan. (This works directly because the example database uses the C collation. With other collations, PostgreSQL needs an index built withtext_pattern_ops.)- A leading wildcard,
LIKE '%4242@%', can match anywhere in the value, so there's no range to read and the table is scanned. A trigram index (below) or full-text search solves this.
Other common causes: OR across different columns (often better as UNION), <> and NOT IN, which match most rows, and comparing a column with a value of another type.
Selectivity: when an index isn't worth it
-- Keep plans simple and repeatable: no parallel workers
SET max_parallel_workers_per_gather = 0;
-- 200,000 orders with deterministic, evenly spread data
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
email TEXT NOT NULL,
placed_on DATE NOT NULL,
status TEXT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO big_orders
SELECT g,
(g * 7919) % 20000 + 1,
'Customer' || ((g * 7919) % 20000 + 1) || '@Example.com',
DATE '2024-01-01' + (g % 1000),
CASE WHEN g % 100 = 0 THEN 'cancelled' WHEN g % 10 = 0 THEN 'pending' ELSE 'shipped' END,
(g % 500) + 0.99
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- Selectivity: an index helps when the condition matches few rows
CREATE INDEX big_orders_status_ix ON big_orders (status);
ANALYZE big_orders;
SELECT status, COUNT(*) AS orders,
ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM big_orders GROUP BY status ORDER BY orders;
-- 1% of rows: the index is used
EXPLAIN (COSTS OFF) SELECT order_id FROM big_orders WHERE status = 'cancelled';
-- 90% of rows: reading the whole table is cheaper than 180,000 index lookups
EXPLAIN (COSTS OFF) SELECT order_id FROM big_orders WHERE status = 'shipped';
status | orders | pct
-----------+--------+------
cancelled | 2000 | 1.0
pending | 18000 | 9.0
shipped | 180000 | 90.0
(3 rows)
QUERY PLAN
-----------------------------------------------------
Index Scan using big_orders_status_ix on big_orders
Index Cond: (status = 'cancelled'::text)
(2 rows)
QUERY PLAN
--------------------------------------
Seq Scan on big_orders
Filter: (status = 'shipped'::text)
(2 rows)
An index lookup costs more per row than a sequential read, because each match may need a separate page read from a different part of the table. So an index pays off only when the condition is selective, matching a small fraction of the rows:
status = 'cancelled'matches 1% of the rows, and the index is used.status = 'shipped'matches 90%. Following 180,000 index entries would be far slower than reading the table once, so the planner ignores the index.
The planner makes this choice using statistics about each column's values, gathered by ANALYZE (which runs automatically). Wrong or outdated statistics are a common cause of bad plans (article 67). The practical lessons: don't index columns with a few common values just because they appear in WHERE clauses, and don't be surprised when an index isn't used for a query that matches most of the table.
Partial and covering indexes
-- Keep plans simple and repeatable: no parallel workers
SET max_parallel_workers_per_gather = 0;
-- 200,000 orders with deterministic, evenly spread data
CREATE TABLE big_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
email TEXT NOT NULL,
placed_on DATE NOT NULL,
status TEXT NOT NULL,
amount NUMERIC(10, 2) NOT NULL
);
INSERT INTO big_orders
SELECT g,
(g * 7919) % 20000 + 1,
'Customer' || ((g * 7919) % 20000 + 1) || '@Example.com',
DATE '2024-01-01' + (g % 1000),
CASE WHEN g % 100 = 0 THEN 'cancelled' WHEN g % 10 = 0 THEN 'pending' ELSE 'shipped' END,
(g % 500) + 0.99
FROM generate_series(1, 200000) AS g;
ANALYZE big_orders;
-- A partial index covers only the rows a query cares about
CREATE INDEX big_orders_pending_ix ON big_orders (placed_on) WHERE status = 'pending';
-- A covering index stores extra columns, so the query never reads the table
CREATE INDEX big_orders_cust_cover_ix ON big_orders (customer_id) INCLUDE (amount);
VACUUM ANALYZE big_orders;
SELECT indexrelname AS index_name, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'big_orders'
ORDER BY pg_relation_size(indexrelid) DESC, indexrelname;
EXPLAIN (COSTS OFF)
SELECT placed_on FROM big_orders WHERE status = 'pending' AND placed_on = DATE '2026-01-01';
EXPLAIN (COSTS OFF)
SELECT SUM(amount) FROM big_orders WHERE customer_id = 4242;
index_name | size
--------------------------+---------
big_orders_cust_cover_ix | 6184 kB
big_orders_pkey | 4408 kB
big_orders_pending_ix | 136 kB
(3 rows)
QUERY PLAN
-----------------------------------------------------------
Index Only Scan using big_orders_pending_ix on big_orders
Index Cond: (placed_on = '2026-01-01'::date)
(2 rows)
QUERY PLAN
--------------------------------------------------------------------
Aggregate
-> Index Only Scan using big_orders_cust_cover_ix on big_orders
Index Cond: (customer_id = 4242)
(3 rows)
- A partial index has a
WHEREclause and indexes only matching rows. The index of pending orders by date is 136 kB, a fraction of a full index, because only 9% of rows are pending, and it's used by queries with the same condition. Partial indexes suit queues and rare states: unprocessed jobs, open tickets, active users. A partial unique index can enforce rules like "one active subscription per customer". SQL Server calls them filtered indexes. MySQL and Oracle have no direct equivalent. - A covering index contains every column a query needs, so the query can be answered by an Index Only Scan without reading the table.
INCLUDE (amount)adds a column to the leaf entries without making it part of the sort key. The sum of a customer's order amounts is computed from the index alone. SQL Server also supportsINCLUDE. In MySQL, add the column to the index key instead.
Index-only scans in PostgreSQL also depend on the table's visibility map being up to date, which VACUUM maintains.
Other kinds of index
B-trees handle most needs. PostgreSQL has other index types for other operators:
| Type | Good for |
|---|---|
| B-tree | =, ranges, sorting, prefix LIKE |
| Hash | = only. Rarely better than a B-tree |
| GIN | values containing many items: JSON (@>, article 43), arrays, full-text search, trigrams |
| GiST | ranges and overlaps (exclusion constraints, article 52), geometry, nearest-neighbour searches |
| BRIN | very large tables whose physical order follows a column, such as append-only logs by time. Tiny, but approximate |
Other databases have their own: SQL Server's clustered index stores the table itself in key order (InnoDB in MySQL always does this with the primary key), and columnstore indexes speed up analytics. Oracle has bitmap indexes for low-cardinality columns in data warehouses.
Full-text search and trigram indexes
LIKE '%word%' is a poor way to search text: it can't use a B-tree, it doesn't know that "tents" and "tent" are the same word, and it can't rank results. Full-text search handles words properly:
-- Full-text search: match words, not character patterns
CREATE TABLE guides (
guide_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
search TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || body)) STORED
);
INSERT INTO guides (guide_id, title, body) VALUES
(1, 'Pitching a tent in wind', 'Angle the pegs, tighten the guy lines and pitch with the door downwind.'),
(2, 'Choosing a head torch', 'Brightness matters less than battery life when you camp for several nights.'),
(3, 'Packing for wet weather', 'A waterproof tent and dry bags keep gear dry; pack the tent last.'),
(4, 'Lanterns for camping', 'A lantern lights the whole tent, while a torch lights the path.');
CREATE INDEX guides_search_ix ON guides USING gin (search);
-- Words are reduced to stems: "tents", "pitching" and "pitched" all match
SELECT to_tsvector('english', 'Pitching tents in windy weather') AS vector;
-- websearch_to_tsquery understands quotes, "or" and -exclusions, like a search box
SELECT guide_id, title,
ROUND(ts_rank(search, query)::numeric, 3) AS rank
FROM guides, websearch_to_tsquery('english', 'tent or torch') AS query
WHERE search @@ query
ORDER BY rank DESC, guide_id;
SELECT guide_id, title
FROM guides
WHERE search @@ websearch_to_tsquery('english', 'tent -wind')
ORDER BY guide_id;
-- Trigram indexes make LIKE '%...%' searches fast
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT similarity('lantern', 'lanterns') AS close_words, similarity('lantern', 'torch') AS unrelated;
vector
------------------------------------------
'pitch':1 'tent':2 'weather':5 'windi':4
(1 row)
guide_id | title | rank
----------+-------------------------+-------
4 | Lanterns for camping | 0.061
3 | Packing for wet weather | 0.038
1 | Pitching a tent in wind | 0.030
2 | Choosing a head torch | 0.030
(4 rows)
guide_id | title
----------+-------------------------
3 | Packing for wet weather
4 | Lanterns for camping
(2 rows)
close_words | unrelated
-------------+-----------
0.7 | 0
(1 row)
to_tsvector('english', text)breaks text into words, drops common stop words such as "in", and reduces each word to its stem: "Pitching" becomespitch, "tents" becomestent. The positions are kept for ranking.- A query is a
tsquery.websearch_to_tsqueryaccepts search-box syntax:tent or torch,"quoted phrases", and-wordto exclude. The@@operator tests whether a document matches. ts_rankscores matches by how often and where the words occur, so the best matches come first. The lantern guide mentions both "torch" and "tent", so it ranks highest.- Storing the vector in a generated column (article 52) and indexing it with GIN makes searches fast on large tables.
tent -windexcludes the guide about pitching in wind.
For fuzzy matching and fast LIKE '%...%', the pg_trgm extension breaks strings into three-character pieces (trigrams). similarity compares strings, 'lantern' and 'lanterns' share most trigrams, and a GIN index with gin_trgm_ops lets LIKE, ILIKE and regular expression searches (article 42) use an index.
MySQL has FULLTEXT indexes with MATCH ... AGAINST, SQL Server has full-text indexes with CONTAINS and FREETEXT, and SQLite has the FTS5 extension. For large-scale search with typo tolerance, facets and many languages, dedicated search engines such as Elasticsearch or OpenSearch are often used alongside the database.
The cost of indexes
Indexes aren't free:
- Writes get slower. Every insert, and every update or delete that touches an indexed column, must update every index on the table. A table with ten indexes does about ten times the index work per insert.
- They take space, on disk and in memory. The covering index above is larger than the primary key.
- The planner has more to consider, and unused indexes still cost on every write.
So index for the queries you actually run, check plans with EXPLAIN, and remove indexes that aren't used: PostgreSQL's pg_stat_user_indexes view counts how often each index is scanned. Indexes worth creating almost always include:
- the primary key and unique constraints (created automatically)
- foreign key columns, used by joins and by parent deletes (article 53)
- columns in frequent, selective
WHEREconditions, joins andORDER BY ... LIMITqueries
What's current
- PostgreSQL 19 (November 2026) added a core
REPACKcommand, which rebuilds a bloated table and its indexes to reclaim space, taking over the jobs ofVACUUM FULLandCLUSTER. - PostgreSQL 18 added B-tree skip scan, which makes multicolumn indexes usable for conditions that leave out leading columns with few distinct values, and allows GIN indexes to be built in parallel.
- PostgreSQL 17 sped up B-tree searches with many
INvalues, among other planner improvements. - MySQL 8.0 added invisible indexes, which let you test the effect of dropping an index safely, and descending and functional indexes.
Common questions
Why isn't my index being used?
The condition may wrap the column in a function or type conversion, start a LIKE with a wildcard, skip the leading column of a composite index, or match too many rows to be worth it. Check with EXPLAIN, and make sure statistics are current with ANALYZE.
Does column order matter in a composite index?
Yes. Put equality columns first and range or sort columns after them. An index on (a, b) helps queries on a but not efficiently on b alone.
Should I index every column used in a WHERE clause? No. Index selective conditions used by frequent queries. Each index slows down writes and uses space.
How do I make case-insensitive searches fast?
Create an expression index on lower(column) and query with lower(column) = .... Or use a case-insensitive collation.
How do I speed up LIKE '%text%'?
A trigram GIN index in PostgreSQL. For searching words in documents, use full-text search.
Do foreign keys create indexes? Not in PostgreSQL, SQL Server or Oracle. MySQL's InnoDB creates them. Add them yourself.
Summary
- An index is a sorted structure, usually a B-tree, that leads directly to matching rows.
EXPLAINshows whether a query scans the table or uses an index.- Composite indexes follow the leftmost prefix rule: equality columns first, then ranges or sort columns.
- Functions on the column, leading wildcards and type mismatches prevent index use. Expression indexes and rewritten conditions fix them.
- Indexes help selective conditions. The planner ignores them for conditions matching much of the table.
- Partial indexes cover a subset of rows, and covering indexes enable index-only scans.
- GIN, GiST and BRIN serve JSON, arrays, text search, ranges and huge append-only tables.
- Full-text search matches stemmed words with ranking. Trigram indexes speed up
LIKE '%...%'. - Every index slows writes and uses space: index what your queries need, and drop what they don't use.
Practice questions
Queries filter big_orders by status = 'pending' and sort by placed_on DESC with FETCH FIRST 20 ROWS ONLY. Suggest an index.
Answer
CREATE INDEX big_orders_status_date_ix ON big_orders (status, placed_on DESC);
Equality on status first, then the sort column, so the database can read the newest pending orders directly from the index and stop after 20. A partial index, ON big_orders (placed_on DESC) WHERE status = 'pending', is a smaller alternative if only pending orders are queried this way.
Rewrite WHERE EXTRACT(YEAR FROM placed_on) = 2025 so that an index on placed_on can be used.
Answer
WHERE placed_on >= DATE '2025-01-01' AND placed_on < DATE '2026-01-01'
An index on (customer_id, placed_on) exists. Which of these conditions can use it efficiently: (a) customer_id = 7, (b) placed_on = DATE '2025-06-01', (c) customer_id = 7 AND placed_on > DATE '2025-01-01'?
Answer
(a) and (c). Both start with the leading column. (b) uses only the second column, so its entries are scattered through the index: at best the whole index is scanned, unless the database supports skip scan and the leading column has few distinct values.
Why does PostgreSQL scan the table for status = 'shipped' even though status is indexed?
Answer
90% of the rows match. Fetching 180,000 rows one index entry at a time would be slower than reading the whole table sequentially, so the planner chooses the sequential scan.
What does to_tsvector('english', 'Pitching tents in windy weather') return, and why don't the words appear as written?
Answer
'pitch':1 'tent':2 'weather':5 'windi':4. Words are reduced to their stems so that different forms match each other, and the stop word "in" is dropped. The numbers are word positions.
Previous: Generating Keys: Identity Columns, Sequences and UUIDs

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.