Cheatsheet Pages / SQL Cheatsheet

How to speed up frequent lookups in SQL — CREATE INDEX

Queries filtering on dept_id are scanning the whole employees table and getting slow.

Every example runs against the cheatsheet's sample tables — departments(id, name), employees(id, name, dept_id, salary, manager_id, hired_on) and orders(id, emp_id, amount, ordered_on) — and was executed and verified against SQLite, so you can paste it in and get the same result.

CREATE INDEX idx_employees_dept ON employees(dept_id);
-- After this, WHERE dept_id = ? uses the index instead of scanning the whole table
-- Verify: EXPLAIN QUERY PLAN in SQLite, EXPLAIN in MySQL / PostgreSQL
-- Every index slows writes down, so index the columns you actually filter on — not everything
SQL Cheatsheet one-page card — queries that actually work
The full one-page card — SQL Cheatsheet. Get the complete cheatsheet on GitHub