What is a database index and when should I add one?
An index is a sorted structure that lets the database find rows without scanning the whole table. Add one to columns you filter, join or sort by frequently.
CREATE INDEX idx_videos_track ON videos(track);Without it, WHERE track = 'python' reads every row. With it, the database jumps straight to the matching ones — the difference between O(n) and O(log n).
#Where indexes pay off
- Columns in
WHEREclauses - Foreign keys used in
JOINs - Columns in
ORDER BY - Columns with a
UNIQUEconstraint (which creates one automatically)
Primary keys are indexed for you.
#What they cost
Writes get slower. Every INSERT, UPDATE and DELETE must update every affected index.
They use disk. A large index on a large table is not free.
So do not index everything. Index what your slow queries actually filter on.
#Composite indexes and column order
CREATE INDEX idx_track_views ON videos(track, views);This serves WHERE track = ?, and WHERE track = ? AND views > ?. It does not help WHERE views > ? alone — an index can only be used from its leftmost column onward. Think of a phone book sorted by surname then first name: useless for finding everyone called Dominic.
#Things that stop an index being used
WHERE LOWER(email) = 'a@b.com' -- function on the column
WHERE views + 1 > 100 -- arithmetic on the column
WHERE title LIKE '%python%' -- leading wildcardRewrite so the column stands alone, or create a functional index on the expression.
#Measure, do not guess
EXPLAIN ANALYZE SELECT * FROM videos WHERE track = 'python';If you see "Seq Scan" on a large table where you expected an index, the index is missing or unusable. This one command answers most database performance questions.