SQLSQL
AdvancedLesson 13 of 15

Indexes & Query Plan (EXPLAIN) – SQL

Why queries are slow and how B-tree indexes help.

An index is an additional, sorted data structure (usually a B-tree) that lets the database find rows without reading the whole table (*sequential/full table scan*). The price: writes become slower and the index takes up space. Primary keys and UNIQUE constraints automatically create an index; foreign keys in PostgreSQL and SQLite get none – you create those yourself.

CREATE INDEX idx_bestellungen_kunde ON bestellungen (kunde_id);
CREATE UNIQUE INDEX idx_kunden_email ON kunden (email);          -- requires an email column
CREATE INDEX idx_bestellungen_kunde_datum ON bestellungen (kunde_id, datum);   -- composite
DROP INDEX idx_bestellungen_kunde;

For a composite index, the leftmost prefix principle applies: (kunde_id, datum) helps with WHERE kunde_id = 1 and WHERE kunde_id = 1 AND datum > ..., but hardly with WHERE datum > ... alone. With EXPLAIN you can see whether the database uses the index.

-- SQLite
EXPLAIN QUERY PLAN SELECT * FROM bestellungen WHERE kunde_id = 1;
--   SEARCH bestellungen USING INDEX idx_bestellungen_kunde (kunde_id=?)

-- PostgreSQL (actually executes and measures!)
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM bestellungen WHERE kunde_id = 1;
--   Index Scan using idx_bestellungen_kunde ... vs. Seq Scan on bestellungen

-- MySQL
EXPLAIN SELECT * FROM bestellungen WHERE kunde_id = 1;
WarningAn index is not used if you wrap the column in a function (WHERE YEAR(datum) = 2024, WHERE LOWER(name) = ...) or use leading wildcards (LIKE '%son'). Write it sargable: datum >= '2024-01-01' AND datum < '2025-01-01' – or create a functional index (CREATE INDEX ... ON kunden (LOWER(name)), PostgreSQL/SQLite).
  • Covering index: contains all required columns – the table is not touched at all (*index-only scan*).
  • Partial index (PostgreSQL, SQLite): CREATE INDEX ... ON bestellungen (datum) WHERE status = 'offen' – small and fast for frequently used subsets.
  • Selectivity: indexes pay off on columns with many distinct values; for status with three values, a normal index rarely helps.
  • Statistics: after large loads, run ANALYZE (PostgreSQL/SQLite) so the planner makes good decisions.