Indexes and query tuning as the first step
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's "My orders" page now takes two seconds, and the team wants to rent three more servers. Before paying for hardware, find out why one query is slow.
Your turn: the slow orders page
ShopLite has 5 million orders, and "My orders" asks for the orders of one customer. The page takes two seconds. Before reading on, think about three questions and write a one-line answer to each:
- What must MySQL do if it has no help finding customer 4242's rows?
- How would you find out which query is slow, instead of guessing?
- Would a second database server make this one query faster? Why or why not?
Full scan vs index lookup
An index is a separate sorted structure (a B+tree in MySQL) that maps column values to table rows, so the database can jump straight to the matching rows instead of reading the whole table.
A scan checks every row; an index jumps to the matches. This program builds 1,000,000 orders and counts the work each way.
Example 1 · A million rows: scan vs hash index vs sorted index
import java.time.LocalDate;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.NavigableMap;import java.util.TreeMap;
record Order(int id, int customerId, LocalDate orderedOn) { }
public class IndexVsScanDemo { public static void main(String[] args) { List<Order> table = new ArrayList<>(); LocalDate start = LocalDate.of(2026, 1, 1); for (int id = 1; id <= 1_000_000; id++) { table.add(new Order(id, id % 50_000, start.plusDays(id % 365))); }
// 1. Full scan: look at every row int checked = 0; int found = 0; for (Order o : table) { checked++; if (o.customerId() == 4242) { found++; } } System.out.println("Full scan: checked " + checked + " rows, found " + found);
// 2. Hash index on customerId: one lookup, then only the matching rows Map<Integer, List<Order>> byCustomer = new HashMap<>(); for (Order o : table) { byCustomer.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o); } List<Order> mine = byCustomer.get(4242); System.out.println("Hash index: 1 lookup, then " + mine.size() + " rows");
// 3. Sorted index on the date: jump to the start of a range, read only that range NavigableMap<LocalDate, List<Order>> byDate = new TreeMap<>(); for (Order o : table) { byDate.computeIfAbsent(o.orderedOn(), k -> new ArrayList<>()).add(o); } NavigableMap<LocalDate, List<Order>> diwaliWeek = byDate.subMap(LocalDate.of(2026, 11, 6), true, LocalDate.of(2026, 11, 12), true); int rows = diwaliWeek.values().stream().mapToInt(List::size).sum(); System.out.println("Sorted index: " + diwaliWeek.size() + " date keys, " + rows + " rows for 6-12 Nov"); }}Full scan: checked 1000000 rows, found 20 Hash index: 1 lookup, then 20 rows Sorted index: 7 date keys, 19173 rows for 6-12 Nov
What this code does
- The scan checks all 1,000,000 rows to find customer 4242's 20 orders. The
HashMapindex finds the same 20 rows with one lookup. - The
TreeMapindex is sorted by date, sosubMapjumps to 6 November and reads only those 7 dates. That is how a B+tree index answers a range query.
A full table scan reads every row to find the few that match, so its cost grows with the table: twice the rows, twice the work. An index lookup stays almost flat. On 500 rows nobody notices; on ShopLite's millions of orders it is the difference between 2 ms and 2 seconds.
A hash index answers "equal to" questions. A sorted index (the TreeMap here, a B+tree in MySQL) also answers ranges such as "orders placed from 6 to 12 November". The Indexes lessons in the SQL and Databases section show how to create them.
Finding slow queries: slow query log and EXPLAIN
EXPLAIN shows how MySQL plans to run a query: the access type, the index it picks and how many rows it expects to examine, without running the query itself.
Switch on the slow query log, then ask MySQL how it would run the worst query.
SET GLOBAL slow_query_log = 'ON';SET GLOBAL long_query_time = 0.5; -- log anything slower than 500 ms
EXPLAIN SELECT order_id, customer_idFROM ordersWHERE status = 'PLACED' AND ordered_at < '2026-10-01';Example 2 · EXPLAIN before and after adding a composite index
Runs in: MySQL 8.4 with a ShopLite orders table of about 500,000 rows
EXPLAIN SELECT order_id, customer_id FROM ordersWHERE status = 'PLACED' AND ordered_at < '2026-10-01';
CREATE INDEX idx_orders_status_ordered_at ON orders (status, ordered_at);
EXPLAIN SELECT order_id, customer_id FROM ordersWHERE status = 'PLACED' AND ordered_at < '2026-10-01';+----+-------------+--------+------------+------+---------------+------+---------+------+--------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------+------------+------+---------------+------+---------+------+--------+----------+-------------+ | 1 | SIMPLE | orders | NULL | ALL | NULL | NULL | NULL | NULL | 498230 | 3.33 | Using where | +----+-------------+--------+------------+------+---------------+------+---------+------+--------+----------+-------------+ +----+-------------+--------+------------+-------+------------------------------+------------------------------+---------+------+-------+----------+-----------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------+------------+-------+------------------------------+------------------------------+---------+------+-------+----------+-----------------------+ | 1 | SIMPLE | orders | NULL | range | idx_orders_status_ordered_at | idx_orders_status_ordered_at | 47 | NULL | 18210 | 100.00 | Using index condition | +----+-------------+--------+------------+-------+------------------------------+------------------------------+---------+------+-------+----------+-----------------------+
What this code does
- Before:
type = ALLwithkey = NULLand about 498,000 rows examined: a full scan for a query that returns a few thousand rows. - After:
type = rangeonidx_orders_status_ordered_atwith about 18,000 rows. The row estimates differ on your data; the change fromALLtorangeis what matters.
The slow query log records every statement that takes longer than long_query_time seconds. Group it by query shape and sort by total time (count × average time): a 50 ms query that runs 10,000 times an hour costs more than one 3-second report.
In the plan, read three columns first: type (ALL means full scan; ref, range or const mean an index is used), key (which index) and rows (how many rows MySQL expects to examine).
Order of execution
Tune a slow page, in order
Put the steps in the order a careful developer follows.
SET GLOBAL needs admin rights and lasts until the server restarts. On a managed database, set these in the parameter settings instead.N+1 queries and fetching only needed columns
N+1 queries is a pattern where the app runs one query to load a list and then one more query for each item in it: 20 orders cost 21 queries.
The first loop below is the N+1 trap; the second version fetches all the customers at once.
Example 3 · N+1 queries vs one batched query
import java.util.HashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.IntStream;
record OrderRow(int id, int customerId) { }
class FakeDb { int queries = 0; final Map<Integer, String> customers = Map.of(1, "Asha Rao", 2, "Ravi Kumar", 3, "Meena Iyer", 4, "Kabir Singh");
List<OrderRow> latestOrders(int n) { queries++; return IntStream.rangeClosed(1, n).mapToObj(i -> new OrderRow(100 + i, (i % 4) + 1)).toList(); }
String customerName(int id) { queries++; return customers.get(id); }
Map<Integer, String> customerNames(Set<Integer> ids) { queries++; Map<Integer, String> result = new HashMap<>(); ids.forEach(id -> result.put(id, customers.get(id))); return result; }}
public class NPlusOneDemo { public static void main(String[] args) { FakeDb db = new FakeDb(); List<OrderRow> orders = db.latestOrders(20); for (OrderRow o : orders) { db.customerName(o.customerId()); } System.out.println("N+1 version: " + db.queries + " queries for 20 orders");
FakeDb db2 = new FakeDb(); List<OrderRow> orders2 = db2.latestOrders(20); Set<Integer> ids = orders2.stream().map(OrderRow::customerId).collect(Collectors.toCollection(LinkedHashSet::new)); Map<Integer, String> names = db2.customerNames(ids); System.out.println("Batched: " + db2.queries + " queries for 20 orders (" + ids.size() + " customers)"); System.out.println("First line: order " + orders2.get(0).id() + " by " + names.get(orders2.get(0).customerId())); }}N+1 version: 21 queries for 20 orders Batched: 2 queries for 20 orders (4 customers) First line: order 101 by Ravi Kumar
What this code does
- The loop calls
customerNameonce per order: 1 query for the list plus 20 lookups, 21 in all. - The batched version collects the distinct customer ids and fetches them with one
IN (...)query: 2 queries in total, whatever the page size.
Each query is fast alone, but the network round trips add up. Fix it with one batched query (WHERE customer_id IN (...)) or a join; in JPA, use a fetch join or @EntityGraph, as the Spring Data JPA section showed.
The second habit: select only the columns the page shows. SELECT * on a product with a long description moves twenty times more bytes than SELECT product_id, name, price.
Predict the output
Count the queries
How many queries does one page view run?
Round 1 of 3
What indexes cost, and why tune before adding servers
The leftmost prefix rule says an index on (a, b) helps filters on a, or on a and b, but not a filter on b alone.
Every index also costs write time and memory. This program counts the extra writes for 100,000 inserts with three indexes.
Example 4 · Every index adds work to every insert
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class IndexCostDemo { record Row(int id, int customerId, String status, long orderedAt) { }
public static void main(String[] args) { int inserts = 100_000;
List<Row> table = new ArrayList<>(); Map<Integer, List<Integer>> byCustomer = new HashMap<>(); TreeMap<String, Integer> byStatusDate = new TreeMap<>(); TreeMap<Long, Integer> byDate = new TreeMap<>();
long writesNoIndex = 0; long writesWithIndexes = 0; String[] statuses = {"PLACED", "SHIPPED", "DELIVERED", "CANCELLED"}; for (int id = 1; id <= inserts; id++) { Row r = new Row(id, id % 5_000, statuses[id % 4], 1_760_000_000L + id * 60L); table.add(r); writesNoIndex++; writesWithIndexes++;
byCustomer.computeIfAbsent(r.customerId(), k -> new ArrayList<>()).add(id); byStatusDate.put(r.status() + "|" + r.orderedAt() + "|" + id, id); byDate.put(r.orderedAt(), id); writesWithIndexes += 3; // every index must be updated too } long indexEntries = byStatusDate.size() + byDate.size() + byCustomer.values().stream().mapToLong(List::size).sum();
System.out.println("Rows inserted: " + table.size()); System.out.println("Writes with no index: " + writesNoIndex + " (1 per row)"); System.out.println("Writes with 3 indexes: " + writesWithIndexes + " (4 per row)"); System.out.println("Extra index entries: " + indexEntries + " to store and keep in memory"); }}Rows inserted: 100000 Writes with no index: 100000 (1 per row) Writes with 3 indexes: 400000 (4 per row) Extra index entries: 300000 to store and keep in memory
What this code does
- With no index, an insert is one write. With three indexes, each insert also updates three sorted or hashed structures: four writes per row.
- The 300,000 extra index entries must be stored and, to be fast, kept in memory. That is why unused indexes should be dropped.
Every INSERT, every UPDATE of an indexed column and every DELETE must also change each index on the table, and each index takes disk space and memory. So index the columns your frequent queries filter, join and sort on, and drop indexes that no query uses.
- Good candidates: columns in
WHERE,JOIN ... ONandORDER BYof frequent queries. - A composite index
(status, ordered_at)helps queries that filter onstatusfirst (the leftmost prefix). - Poor candidates: columns with very few distinct values used alone (such as
is_active), and write-heavy tables with rare reads.
Tuning comes before scaling because it is cheap and it multiplies: a missing index makes every extra server just as slow, and replicas copy the same bad query plan. The order is: find slow queries, fix indexes and queries, then cache, then read replicas, then sharding.
Next step
Check your understanding
11 quick questions