SteelReed

Search

Search posts, questions…

4. Database & SQL

Databases: indexes, EXPLAIN, N+1, pagination and soft delete

Why a correct SQL query can still be slow: B+trees, clustered and composite indexes, covering indexes, sargability, reading EXPLAIN, N+1, keyset pagination and the real cost of soft delete.

17 Nov 20269 min readSenior

–

1. The problem

The "my orders" screen took 3 ms at launch and 1.8 seconds a year later. The log shows 51 SQL statements per page view; page 2,000 of the admin list takes 4 seconds; a customer who deletes their account and signs up again with the same email gets a duplicate error.

2. Key idea

An index keeps data sorted by its columns, finding rows in O(log n) instead of reading them all. In InnoDB the primary key is the clustered index (leaves hold the whole row); secondary indexes hold the column values plus the PK, so the PK should be short and increasing (UUID v4 fails both). An index on (customer_id, status, created_at) is sorted like a phone book: it only works by leftmost prefix.

Query Uses index (customer_id, status, created_at)?
WHERE customer_id = ? AND status = ? ORDER BY created_at Yes, no sort needed
WHERE customer_id = ? AND created_at > ? Only the customer_id part
WHERE status = ? No (missing the first column)
WHERE DATE(created_at) = ? (index on created_at) No: the column is wrapped in a function
Technique Use when Don't use when
Covering index a hot query needs only a few columns you'd have to stuff large columns into the index
OFFSET small page counts, "jump to page 5" deep pages on big tables
Keyset (cursor) infinite scroll, APIs, deep pages you need to jump to arbitrary pages
Soft delete (deleted_at) you need restore or history the law requires real deletion

3. In SQL

SQL
-- Sargable: compare the bare column with a half-open range
SELECT * FROM orders
WHERE created_at >= '2026-01-10' AND created_at < '2026-01-11';  -- type: range, rows: 1440
-- DATE(created_at) = '2026-01-10'                                 -- type: ALL, rows: 50170
 
-- Keyset: flat speed on every page, needs an index on (created_at, id)
SELECT id, total, created_at FROM orders
WHERE (created_at, id) < (:lastCreatedAt, :lastId)
ORDER BY created_at DESC, id DESC
LIMIT 20;
 
-- Soft delete that still forbids two active accounts with one email (MySQL)
ALTER TABLE account
  ADD active_email VARCHAR(255) AS (CASE WHEN deleted_at IS NULL THEN email END) STORED,
  ADD UNIQUE (active_email);
-- PostgreSQL: CREATE UNIQUE INDEX ON account (email) WHERE deleted_at IS NULL;

EXPLAIN only estimates; EXPLAIN ANALYZE runs the query. Look at type (ALL is a full scan), key/key_len (how many index columns are used), Extra (Using filesort, Using index). PostgreSQL doesn't index foreign key columns automatically.

N+1 in JPA and the cost of indexes
  • N+1: loading 50 orders and touching lazy order.getItems() is 1 + 50 statements. Fix: JOIN FETCH (one collection per query), @EntityGraph, hibernate.default_batch_fetch_size (batched into IN (...)), or DTO projections with just the needed columns. Turn on SQL logging or count queries in tests to catch it.
  • Cost of indexes: every INSERT updates every index; (a) is redundant when (a, b) exists. Low-cardinality columns (status) rarely deserve their own index, unless it serves sort + LIMIT.
  • Soft delete: every query must remember deleted_at IS NULL (Hibernate's @SQLRestriction helps), and indexes should be partial or include deleted_at.

4. Working with AI

Hand to AI: proposing indexes from a list of hot queries, reading long EXPLAIN output, generating 1 million test rows, a test counting an endpoint's queries.

Check yourself in AI-written code:

  • Composite indexes put equality columns first, sort/range last.
  • No WHERE column is wrapped in a function or implicitly cast.
  • EXPLAIN ANALYZE was run on production-sized data, not a 10-row table.
  • List endpoints have a query-count test (no N+1).
  • Deep-pagination APIs use keyset; uniqueness on soft-deleted tables applies only to active rows.

5. Exercises

Exercise 1: Read an EXPLAIN with Using filesort

SELECT id, total, created_at FROM orders WHERE status = 'PAID' ORDER BY created_at DESC LIMIT 50 shows type: ALL, Extra: Using where; Using filesort. The AI suggests "add an index on status". Is that enough? Fix it.

Solution 1
  • type: ALL: no index starts with status. Using filesort: the DB sorts every PAID row before taking 50, so LIMIT doesn't shorten the scan.
  • An index on (status) alone filters but still sorts. Use (status, created_at): the DB jumps to PAID, reads backward by created_at and stops after 50 rows (Backward index scan, no filesort).
  • To also skip the table lookup for total: (status, created_at, total).

Exercise 2: Move a paginated API to keyset

GET /orders?page=2000&size=20 takes 4 seconds. The AI suggests caching every page. What do you propose, and what do you keep for old clients?

Solution 2
  • OFFSET 40,000 makes the DB read and discard 40,000 rows; caching doesn't help because deep pages rarely repeat and the data keeps changing.
  • New API: GET /orders?size=20&cursor=<opaque>. The server decodes the cursor into (created_at, id), runs the keyset query from section 3, and returns items and next_cursor (null at the end). It needs an index on (created_at, id).
  • Keep the old API for a while and deprecate it, since keyset can't "jump to page 2,000".

Summary

  • B+tree indexes: composites by leftmost prefix, equality first, sort/range last.
  • InnoDB PKs short and increasing; secondary indexes contain the PK.
  • Don't wrap columns in functions; measure with EXPLAIN ANALYZE on real data.
  • N+1: JOIN FETCH, batch fetching, DTO projections; count queries in tests.
  • Deep pages use keyset; soft delete needs uniqueness for active rows only.

Further reading: Transactions, isolation levels and locking.

Practice interview questions on this topic

All SQL & Query Tuning questions →All Data Modeling & Scaling questions →

Loading comments…