SQL Query Performance & Optimisation
Chapter 39 of 40 · Estimated read time: 12 min
A query that works correctly on 1,000 rows may grind to a halt on 10 million. Understanding how the database executes a query — and how to guide it toward an efficient plan — separates an average SQL writer from a data professional. This chapter covers the practical techniques used every day in real analytics and engineering roles.
Reading EXPLAIN Output
Before optimising anything, run EXPLAIN in front of your query to see the execution plan the database chose:
EXPLAIN SELECT o.order_id, c.customer_name, p.product_name FROM orders AS o JOIN customers AS c ON o.customer_id = c.customer_id JOIN products AS p ON o.product_id = p.product_id WHERE c.city = 'Noida';
| Column | What it means | Good sign | Warning sign |
|---|---|---|---|
| type | How rows are found | ref, range, eq_ref | ALL (full scan), index |
| key | Index used (NULL = none) | index name shown | NULL |
| rows | Estimated rows examined | small number | millions of rows |
| Extra | Extra operations needed | Using index | Using filesort, Using temporary |
| type | Meaning |
|---|---|
| const | Primary key or unique lookup — 1 row, fastest possible |
| eq_ref | One row per join from unique/PK index |
| ref | Index lookup returning a small set of rows |
| range | Index range scan (BETWEEN, >, <, IN) |
| index | Full index scan — fast, but still reads all index entries |
| ALL | Full table scan — reads every row ❌ fix this |
SARGable WHERE Clauses — Don't Break the Index
A SARGable (Search ARGument Able) condition lets the database use an index. Wrapping an indexed column in a function or calculation makes it non-SARGable — the index is bypassed.
-- ❌ Slow: function on indexed column — full scan SELECT * FROM orders WHERE YEAR(order_date) = 2026; -- ✅ Fast: range on the column itself — uses index SELECT * FROM orders WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';
Avoid SELECT * in Production Queries
-- ❌ Avoid in production SELECT * FROM orders JOIN customers ON ...; -- ✅ Name only the columns you actually use SELECT o.order_id, o.order_date, o.total_amount, c.customer_name, c.city FROM orders AS o JOIN customers AS c ON o.customer_id = c.customer_id;
Covering Indexes
A covering index contains all the columns a query needs — the database satisfies the entire query from the index without touching the base table. EXPLAIN shows Using index in the Extra column.
-- Query only needs customer_id and total_amount from orders SELECT customer_id, SUM(total_amount) AS revenue FROM orders GROUP BY customer_id; -- A covering index on both columns lets this run entirely from the index: CREATE INDEX idx_orders_cust_amount ON orders (customer_id, total_amount); -- EXPLAIN Extra: "Using index" ← zero table lookups needed
JOIN Performance Tips
-- ✅ Always index foreign key columns (they appear in ON clauses) CREATE INDEX idx_orders_customer ON orders (customer_id); CREATE INDEX idx_orders_product ON orders (product_id); -- ✅ Filter early — reduce rows before the JOIN -- ❌ Slow: join all rows, then filter SELECT o.order_id, c.customer_name FROM orders AS o JOIN customers AS c ON o.customer_id = c.customer_id WHERE c.city = 'Noida' AND o.total_amount > 1000; -- ✅ Equivalent but explicit — same plan in modern optimisers, -- but writing it this way makes intent clear SELECT o.order_id, c.customer_name FROM (SELECT * FROM orders WHERE total_amount > 1000) AS o JOIN (SELECT * FROM customers WHERE city = 'Noida') AS c ON o.customer_id = c.customer_id;
Replace Correlated Subqueries with JOINs or Window Functions
-- ❌ Correlated subquery runs once per row — O(n²) on large tables SELECT product_name, price, (SELECT AVG(price) FROM products p2 WHERE p2.category = p1.category) AS cat_avg FROM products AS p1; -- ✅ Window function — single pass, O(n) SELECT product_name, price, AVG(price) OVER (PARTITION BY category) AS cat_avg FROM products;
| Approach | Passes over data | Scales to millions of rows |
|---|---|---|
| Correlated subquery | 1 subquery per outer row (n passes) | ❌ Exponential slowdown |
| Window function | Single pass | ✅ Linear — stays fast |
| JOIN to aggregated subquery | 2 passes | ✅ Linear |
Use LIMIT for Exploratory Queries
-- During development / exploration, always LIMIT first SELECT * FROM very_large_table WHERE some_condition LIMIT 100; -- preview quickly before removing the LIMIT -- For pagination, use LIMIT + OFFSET (or keyset pagination on large sets) SELECT order_id, order_date, total_amount FROM orders ORDER BY order_date DESC LIMIT 10 OFFSET 20; -- page 3, 10 rows per page
WHERE order_id > last_seen_id LIMIT 10.Optimisation Checklist
Show Answers
-- 1. SARGable rewrite SELECT * FROM orders WHERE order_date >= '2026-10-01' AND order_date < '2026-11-01'; -- 2. Covering index — put the equality column first, -- then the other columns the query needs CREATE INDEX idx_orders_cust_covering ON orders (customer_id, order_id, total_amount); -- EXPLAIN should show: type=ref, Extra=Using index -- 3. Window function replacement SELECT order_id, total_amount, SUM(total_amount) OVER (PARTITION BY customer_id) AS cust_total FROM orders;