Add an index to speed up a query
An index helps columns used in WHERE, JOIN and ORDER BY. Too many indexes slow down writes, so add them for real queries and check with EXPLAIN.
SQL · Add an index to speed up a queryIntermediate
-- Single column
CREATE INDEX idx_orders_customer ON orders (customer_id);
-- Two columns: useful for WHERE status = ? ORDER BY created_at
CREATE INDEX idx_orders_status_date ON orders (status, created_at);
-- Check it is used (look at the "key" column)
EXPLAIN SELECT * FROM orders WHERE status = 'paid' ORDER BY created_at DESC LIMIT 20;indexperformanceexplain