EVIKA.ACADEMY›SQL Tutorial
SQL Tutorial›Performance & Optimisation

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.

The Optimisation Loop
1. Identify slow query
→
2. Run EXPLAIN
→
3. Find bottleneck
→
4. Apply fix
→
5. Measure again

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';
Key columns to read in EXPLAIN output
ColumnWhat it meansGood signWarning sign
typeHow rows are foundref, range, eq_refALL (full scan), index
keyIndex used (NULL = none)index name shownNULL
rowsEstimated rows examinedsmall numbermillions of rows
ExtraExtra operations neededUsing indexUsing filesort, Using temporary
EXPLAIN type values from fastest to slowest
typeMeaning
constPrimary key or unique lookup — 1 row, fastest possible
eq_refOne row per join from unique/PK index
refIndex lookup returning a small set of rows
rangeIndex range scan (BETWEEN, >, <, IN)
indexFull index scan — fast, but still reads all index entries
ALLFull 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.

❌ Non-SARGable (index bypassed)
WHERE YEAR(order_date) = 2026
WHERE LOWER(city) = 'noida'
WHERE price + 100 > 1000
WHERE LEFT(customer_id, 1) = 'C'
✅ SARGable (index used)
WHERE order_date BETWEEN '2026-01-01' AND '2026-12-31'
WHERE city = 'Noida' -- use consistent casing
WHERE price > 900
WHERE customer_id LIKE 'C%'
-- ❌ 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';
The rule: never transform the left-hand side of a WHERE condition. Transform the right-hand side (the constant) instead, so the column value is compared directly.

Avoid SELECT * in Production Queries

❌ SELECT *
Fetches every column, including large TEXT/BLOB fields you do not need. Cannot use a covering index. Breaks if columns are added or reordered. Transfers unnecessary data over the network.
✅ Name your columns
Fetches only what you need. Enables covering indexes (the index contains all needed columns — no table lookup required). Explicit, self-documenting, refactor-safe.
-- ❌ 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
A covering index is one of the highest-impact optimisations available. If a query runs millions of times and touches only a few columns, a covering index can cut execution time by 10–100x.

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;
Modern query optimisers (MySQL 8+, PostgreSQL 14+) are good at reordering JOIN conditions and pushing filters down. Writing clean, explicit queries helps the optimiser — and helps the next person reading the code.

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;
ApproachPasses over dataScales to millions of rows
Correlated subquery1 subquery per outer row (n passes)❌ Exponential slowdown
Window functionSingle pass✅ Linear — stays fast
JOIN to aggregated subquery2 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
LIMIT with OFFSET gets slower as OFFSET grows. OFFSET 100000 makes the database skip 100,000 rows before returning your 10. For deep pagination on large tables, use a keyset: WHERE order_id > last_seen_id LIMIT 10.

Optimisation Checklist

✓
Run EXPLAIN first
Confirm the problem before guessing the fix
✓
Index FK columns
Every column in an ON clause needs an index
✓
Write SARGable WHERE
Never wrap the column in a function
✓
Name columns, not *
Enable covering indexes, reduce data transfer
✓
Filter before JOIN
Smaller inputs → faster join
✓
Use window functions
Replace O(n²) correlated subqueries
✓
LIMIT during development
Never SELECT from a huge table without a limit while exploring
✓
Avoid OFFSET on deep pages
Use keyset pagination for page > 100
✏️ Practice Exercises
1. Rewrite this non-SARGable query to use the index: SELECT * FROM orders WHERE MONTH(order_date) = 10 AND YEAR(order_date) = 2026;
2. You have a query that selects order_id, customer_id, total_amount from orders WHERE customer_id = 'C01'. Design a covering index for it.
3. Replace this correlated subquery with a window function: SELECT order_id, total_amount, (SELECT SUM(total_amount) FROM orders o2 WHERE o2.customer_id = o1.customer_id) AS cust_total FROM orders o1;
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;