Slow Query Interview: One Keyword Made It 40× Slower

An ORDER BY turned a fast page into a filesort over millions of rows. Read EXPLAIN, fix it with the right composite index, and explain the cost.

In this chapter

Interview: one keyword made the page 40× slower

More on Ticket interviews

Keep learning

Overview

the query the page used to run Backward index scan Using index The index is already sorted by created_at inside customer 4521, and it holds every selected column. MySQL reads 20 entries from the end and stops. Nothing to fix. This is the shape to aim for. ORDER BY total sort by a column that is not in the index Using filesort total is not in the index. MySQL reads all 50,000 rows to get total, then sorts. LIMIT 20 only trims the end. If this sort is a real product need: INDEX (customer_id, total, created_at, status). Then it reads 20 entries again. SELECT * ask for every column The index no longer holds every column. Each of 20 entries needs an extra lookup for the full row. Select only the columns the page shows. remove LIMIT ~400 ms + network 50,000 row lookups, all sent over the network and held in app memory. The payload is the problem. idx_cust (customer_id only) Using where The index is sorted by created_at, not DATE(created_at). So DATE() runs on all 50,000 entries. Use a range: created_at >= '2026-10-01' AND created_at < '2026-10-02'. It reads about 40 entries. range on created_at Both index columns narrow the search. The tree jumps to the first entry for that day and stops after the last. This is the fix. LIKE '%refund%' search inside text with a leading wildcard A leading % gives the index no starting point. Every row’s text is scanned. LIKE 'refund%' can use an index. For real search, use a FULLTEXT index or a search engine. OFFSET 10000 jump to page 501 OFFSET still walks the 10,000 entries it throws away. Deeper pages get slower. Keyset pagination: AND created_at < :last_seen ORDER BY created_at DESC LIMIT 20. OR with a column the index does not start with No index starts with status, so MySQL scans all 20M rows. One OR caused a full table scan. UNION ALL of two indexed queries (add INDEX (status, created_at)), or ask whether the page really needs the OR. GROUP BY status count orders per status Using temporary The index is not sorted by status, so MySQL builds a temporary table of groups. INDEX (customer_id, status) lets it group in index order. Or keep a counter table if this runs on every page view. FOR UPDATE lock what you read, inside a transaction ~1 ms, then others wait Still fast, but it locks 20 rows and the gaps between them. New orders there wait until COMMIT. Only lock when you will write. Keep the transaction short. Consider SKIP LOCKED for work queues. Change one thing EXPLAIN (simplified) rows read row lookups Rows read, log scale Disk / buffer I/O Locks held

One keyword made the page 40× slower

A small PR changed one ORDER BY. Read the plan, find the cost, and know what each keyword does. covering index FOR UPDATE Order history p95 went from 30 ms to 1.2 s. New sort column isn’t indexed, so MySQL sorts every row.

Order history page got slow after PR #812

PR #812 added “sort by order total” to order history. p95 went from 30 ms to 1.2 s. DB CPU is at 85%. Worst for big business customers. p95 before p95 after DB CPU 20M rows Restated: the new sort changed the plan. Customers with many orders hurt most.

The diff and the schema

PR #812 diff Also: a column name pasted into SQL. Allow-list it, or it is an injection risk. The index matches ORDER BY created_at. Nothing matches ORDER BY total.

From symptom to plan

Did the plan change? EXPLAIN both versions. Yes: now “Using filesort” and ~50,000 rows instead of 20. Does an index match the new ORDER BY? Compare index columns to the query. No. idx_cust is (customer_id, created_at, status). No total. Why is it worst for big customers? Count rows per customer. Work grows with order count. 50k orders costs 2,500× more than 20. Why CPU and not disk? Check buffer pool hit ratio. Pages are already cached. CPU goes to reading and comparing 50k rows. Anything else wrong in the diff? Read it again. sortColumn is pasted into SQL. It needs an allow-list. ORDER BY created_at Index already sorted. Read 20 entries, stop. ~1 ms. ORDER BY total No matching index. Read 50,000 rows, sort, keep 20. ~250 ms. rows read before rows read after (big customer) more work per request

Be exact about the index and the safety fix

Add index (customer_id, total, created_at, status) Allow-list sort created | total, else 400 Plan test rows ≤ 100, no filesort Three changes: speed, safety, and a guard against regressions. Exact column order: reads 20 entries and covers the SELECT. Fixes the injection hole the AI might copy forward. Turns the plan into a test against future regressions.

No AI from here

What is a filesort, physically? A sort MySQL does itself because no index provides the order. Despite the name, it often runs in memory (sort_buffer_size, per session). Too big for memory? Sorted chunks go to temp files and get merged. LIMIT N keeps a small top-N heap, but every row is still read. spill to disk LIMIT doesn’t cut rows read Read all matches 50,000 rows Sort buffer in memory Spill to temp files? if too big Return top 20 Each new index costs something. What does yours cost? Another tree about the size of idx_cust, competing for cache. Every insert, and updates to total or status, maintain one more tree. If rarely used, limit the sort to recent orders instead. write amplification asks about usage +1 tree per order Competes for buffer pool Every insert updates it How do you prove the fix, not just believe it? Measure it: EXPLAIN ANALYZE on the worst customer, then watch production. After deploy, watch p95 and rows examined (slow log, performance_schema). EXPLAIN ANALYZE worst case verify in prod You add the index on 20M rows at noon. What happens? Minutes of heavy disk and CPU while serving traffic, plus lock and lag risk. It needs a brief metadata lock (table-definition lock) at start and end. A long open transaction blocks it, and new queries queue behind it. Replicas replay it too, so lag spikes. Go off-peak with lock_wait_timeout. metadata lock queue replica lag Long trx on orders ALTER waits for MDL All new queries queue Why not just cache the page in Redis? Cache misses still run the slow query. A cold cache after deploy sends every miss at once. Every new order must evict or update the cached list.

The sort is used by 3% of users

What do you ship? Composite covering index Back to reading 20 entries for everyone. One more index is affordable here. Read latency Write cost Limit the sort to the last 90 days Narrow by date first, then sort a few hundred rows. Product must accept the limit. Cache the page for 60 seconds Hides the cost until the cache goes cold. Users see stale totals. Revert PR #812

Did you show these?

EXPLAIN before vs after Why index order stopped helping Cost scales with orders per customer CPU vs I/O via buffer pool Spotted SQL injection risk Deliberate index column order Priced the index: writes, memory Functions, leading %, OFFSET, OR, FOR UPDATE

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.