← All lessons
Advanced SQL · Lesson 10 of 11

Making queries fast

A query is slow mostly because of how much data it makes the database read. With no help, finding one customer's orders means reading every row of orders and checking each: a full scan. Fine for ten rows, painful for fifty million.

An index is a sorted copy of one or more columns with a pointer back to each row, like the index at the back of a book. With an index on orders(customer_id) the database jumps straight to customer 3's rows. Indexes speed up lookups, ranges, joins and sorts on their columns, but they take space and slow every insert and update a little, so you add them for the queries you actually run. A primary key always has one.

EXPLAIN shows the query plan: what the database will do, step by step. In SQLite it's EXPLAIN QUERY PLAN; PostgreSQL's EXPLAIN ANALYZE also runs the query and shows the real time and rows at each step. SQLite before and after an index:

EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 3;
-- SCAN orders

CREATE INDEX idx_orders_customer ON orders(customer_id);

EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 3;
-- SEARCH orders USING INDEX idx_orders_customer (customer_id=?)

An index on several columns, like (customer_id, ordered_on), is sorted by the first, then the second within it, like a phone book by surname then first name. It helps WHERE customer_id = 3 AND ordered_on > … and WHERE customer_id = 3, but not WHERE ordered_on > … alone, just as a phone book can't find every Sam. Put the column you test with = first. If the index holds every column a query needs, the database never visits the table at all (a covering index).

Some habits stop an index being used. Wrapping the column in a function, like WHERE strftime('%Y', ordered_on) = '2024', means working the function out for every row; ask for a range on the bare column instead. A pattern starting with %, like LIKE '%@example.com', can't use a sorted index either. Comparing a column with a value of a different type can force a conversion on every row.

Other things to look for: SELECT * reading columns nobody uses; a join that fans out to millions of rows and then a DISTINCT to squash them back; filtering after a big join when you could filter before it; a correlated subquery running once per row of a huge table; sorting everything when you only need the top ten.

Data warehouses (BigQuery, Snowflake, Redshift and the like) store each column separately and mostly don't use indexes like these. They split tables into partitions (by date, say) and cluster or sort them so a query can skip whole blocks. There SELECT * really costs: you read, and often pay for, every column. Filter on the partition column and name only the columns you need.

Practice

A plan shows SCAN orders for WHERE customer_id = 42 on a 50-million-row table that's queried thousands of times a day. What's the usual fix?

More info

Quick reference

CREATE INDEX i ON t(a, b)Sorted by a, then b: helps filters on a, or a and b.
EXPLAIN QUERY PLAN / EXPLAIN ANALYZEShow the plan (ANALYZE also runs it, PostgreSQL).
SCAN vs SEARCHSQLite's words for reading everything vs using an index.
col >= a AND col < bA range on the bare column, which an index can use.
covering indexHolds every column the query needs.
partitioning, clusteringHow warehouses skip data.

The other AI and data engineering courses