Full answer
How a B-tree helps
- Keys are kept sorted in a balanced tree of pages. A lookup walks from the root to a leaf in a few steps (three or four levels cover millions of rows) and then jumps to the table row.
- Because keys are sorted, the same index serves equality (=), ranges (<, BETWEEN), sorting (ORDER BY with LIMIT) and prefix matching.
- Primary keys and unique constraints create an index automatically. Foreign keys do not, in PostgreSQL, so add one when you join or delete by that column.
Costs
- Every index uses space and must be updated on each write. Too many indexes slow writes. Index what your queries filter, join and sort on, and remove unused ones.
- The planner decides by estimated cost. For a query that returns most rows, reading the table in order is cheaper, so a sequential scan is correct.
Checking
- EXPLAIN shows the plan without running the query. EXPLAIN ANALYZE runs it and shows real rows and time. Look for the scan type on big tables, the estimated against actual row counts, and extra Sort steps.
- Run ANALYZE so the planner has fresh statistics.
SET client_min_messages = warning;
DROP TABLE IF EXISTS idx_students;
CREATE TABLE idx_students (id serial PRIMARY KEY, email text NOT NULL, city text NOT NULL, score int NOT NULL);
INSERT INTO idx_students (email, city, score)
SELECT 'user' || g || '@example.com', (ARRAY['Pune','Delhi','Goa','Chennai'])[1 + g % 4], g % 100
FROM generate_series(1, 50000) g;
ANALYZE idx_students;
\echo 1. no index on email
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email = 'user777@example.com';
CREATE INDEX idx_students_email ON idx_students (email);
ANALYZE idx_students;
\echo 2. with an index on email
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email = 'user777@example.com';
\echo 3. the primary key is indexed automatically
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE id = 10;
\echo 4. ORDER BY with LIMIT can read the index in order
EXPLAIN (COSTS OFF) SELECT * FROM idx_students ORDER BY email LIMIT 3;
\echo 5. a query that returns almost every row is better served by a table scan
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email > 'a';
\echo 6. indexes that must be maintained on every write
SELECT indexname FROM pg_indexes WHERE tablename = 'idx_students' ORDER BY indexname;
DROP TABLE idx_students;Run with psql against the local PostgreSQL 17 server. COSTS OFF keeps the plans short and stable. Real timings were not measured here. Save it as app.sql and run it with psql -f app.sql. Output (PostgreSQL 17 via psql, run once): 1. no index on email QUERY PLAN ------------------------------------------------- Seq Scan on idx_students Filter: (email = 'user777@example.com'::text) (2 rows) 2. with an index on email QUERY PLAN ----------------------------------------------------- Index Scan using idx_students_email on idx_students Index Cond: (email = 'user777@example.com'::text) (2 rows) 3. the primary key is indexed automatically QUERY PLAN ---------------------------------------------------- Index Scan using idx_students_pkey on idx_students Index Cond: (id = 10) (2 rows) 4. ORDER BY with LIMIT can read the index in order QUERY PLAN ----------------------------------------------------------- Limit -> Index Scan using idx_students_email on idx_students (2 rows) 5. a query that returns almost every row is better served by a table scan QUERY PLAN ------------------------------- Seq Scan on idx_students Filter: (email > 'a'::text) (2 rows) 6. indexes that must be maintained on every write indexname -------------------- idx_students_email idx_students_pkey (2 rows)
Key points
- An index is a sorted structure that avoids scanning the whole table.
- B-trees support equality, range, ordering and prefixes.
- Each index costs space and write time.
- Primary and unique keys are indexed; foreign keys are not automatically.
- Read EXPLAIN output to confirm the plan.
Common mistakes
- Indexing every column.
- Expecting an index to be used for a query that returns most of the table.
- Forgetting to index foreign keys used in joins.
- Reading EXPLAIN without running ANALYZE first.
- Adding indexes in production with a blocking CREATE INDEX instead of CONCURRENTLY.
Follow-ups
- What is CREATE INDEX CONCURRENTLY?
- How does a hash index differ from a B-tree?
- How do you find unused indexes?
Tips
- Say 'sorted structure, logarithmic lookup'.
- Mention write costs.
- Name the scan types.