Database Query Performance

Every query (a command to the database) costs a round trip. N+1 is 1 query for the list + 1 query per row: 20 posts become 21 queries, and the cost adds up…

Your blog page only shows the 20 newest posts with their authors' names. The code is two lines and looks tidy. But when you open the query log (the record of every command sent to the database), 21 queries ran for that one page.

A database is where an app keeps its data, in tables: rows and columns, like a spreadsheet. The database is often the slowest part of a request. Until the query finishes, the server can't send anything, so even the fastest page waits with it. Picture a library. You ask for a list of the 20 newest books, then walk back to the desk 20 times to ask for each book's author, one by one. It's far quicker to ask once: "and the authors of these 20 books, please." And a librarian with a sorted catalogue doesn't need to search every shelf. In your app, the librarian is the database, each question at the desk is one query, and the sorted catalogue is an index.

Terms first

N+1 queries

Here is the query log from the Lab on this page. The posts table has 50,000 rows, the page shows 20 posts, and the authors are stored in the users table:

select * from posts order by created_at desc limit 20;  -- query 1
select * from users where id = 7;                        -- query 2, for the first post
select * from users where id = 3;                        -- query 3, for the second post
-- ... 18 more queries, one for each post

One query for the list of posts, then N more queries for each post's author: 20 + 1 = 21 queries in total. It's called N+1, where N is the number of posts.

This is the Laravel code that produces that log, then the fix. Post::latest()->take(20)->get() gets the 20 newest posts, and $post->author loads the author of a post:

// N+1: 21 queries
$posts = Post::latest()->take(20)->get();
foreach ($posts as $post) {
    echo $post->author->name; // a new query on every pass
}

// Eager loading: 2 queries
$posts = Post::with('author')->latest()->take(20)->get();

with('author') replaces the 20 small queries with one: select * from users where id in (7, 3, 12, ...). The result is always 2 queries.

Posts on the page Without eager loading With with('author')
20 21 queries 2 queries
50 51 queries 2 queries
100 101 queries 2 queries

In Prisma, eager loading is written include: { author: true }. To catch N+1, use Laravel Debugbar or Telescope (tools in Laravel that watch queries), or Model::preventLazyLoading(). preventLazyLoading() throws an error whenever a relation is loaded one at a time, when it's used, inside a loop.

Indexes: a table of contents for a table

Without an index, the database reads every row to find the matching ones (a full table scan). The most common kind of index, a B-tree, keeps the column's values in order, like a library catalogue. So the database can jump straight to the right place. The idea is close to binary search: searching a sorted list by throwing away half of the list at each step. This command creates an index on the created_at column (the time a post was created):

CREATE INDEX idx_posts_created_at ON posts (created_at);

In the Lab, the first query (order by created_at desc limit 20, the 20 newest posts) without an index has to read 50,000 rows and then sort them, about 45 ms. With the index, the database reads the top 20 rows straight from the index, about 1 ms.

The columns most worth indexing are the ones often used in WHERE (filters rows), JOIN (combines tables) and ORDER BY (sorts). Don't index every column. Every index is updated on every INSERT, UPDATE and DELETE (adding, changing and deleting rows), and it takes disk space.

EXPLAIN: ask the database for its plan

EXPLAIN shows how the database would run a query (its plan), without running it. EXPLAIN ANALYZE actually runs it and shows the real times. EXPLAIN ANALYZE exists in PostgreSQL and MySQL 8, two popular databases.

EXPLAIN SELECT id, title FROM posts ORDER BY created_at DESC LIMIT 20;

This is the EXPLAIN result in MySQL, without and with that index:

In MySQL type key rows Extra
Without the index ALL NULL 49,870 Using filesort
With the index index idx_posts_created_at 20 Backward index scan

type: ALL and key: NULL mean a full scan, and rows is the estimated number of rows read. Using filesort means the database has to sort the rows itself, without the index's help. In PostgreSQL, look for Seq Scan (reads every row) or Index Scan (uses an index).

Queries that leave the index unused

Each pair in this block shows the BAD version, then the GOOD version:

-- BAD: every column comes along, including the unused ones
SELECT * FROM users;
-- GOOD
SELECT id, name, email FROM users;

-- BAD: a function on the column, so the created_at index can't be used
SELECT id FROM orders WHERE YEAR(created_at) = 2025;
-- GOOD: a range that can use the index
SELECT id FROM orders WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01';

-- BAD: a leading wildcard, so the B-tree can't be used
SELECT id FROM products WHERE name LIKE '%laptop%';
-- GOOD: full text search
SELECT id FROM products WHERE MATCH(name) AGAINST('laptop');

% in LIKE is a wildcard, which means any text. LIKE 'laptop%' (wildcard at the end) can still use an index, because the start of the text is known.

YEAR() and MATCH ... AGAINST in that block are MySQL and MariaDB syntax. MATCH also needs a FULLTEXT index first: ALTER TABLE products ADD FULLTEXT(name);. Full text search (searching for words with a special index) matches whole words, not parts of words. In PostgreSQL 18 and SQLite, searching for lap didn't find "Laptop Asus 14", while LIKE '%lap%' did.

Other options in other databases:

Database Way When to pick it
PostgreSQL to_tsvector('simple', name) @@ to_tsquery('simple', 'laptop') with a GIN index searching for whole words
PostgreSQL CREATE EXTENSION pg_trgm; then an index USING gin (name gin_trgm_ops) you still need LIKE '%laptop%' (part of a word); the index is used
SQLite an fts5 table: WHERE products_fts MATCH 'laptop' small apps or on a phone; 'lap*' searches for the start of a word

Pagination and caching frequent reads

The exercise version: analyzeQuery and estimateQueryCost

In the exercise, analyzeQuery looks for two patterns in the SQL text and fills issues and suggestions with exactly these texts, in order: SELECT * first, then LIKE.

Query issues suggestions
SELECT * FROM users SELECT * fetches every column Select only the columns you need
SELECT id, name FROM users empty empty
SELECT * FROM products WHERE name LIKE '%laptop%' SELECT * fetches every column, then LIKE with a leading wildcard Select only the columns you need, then Use Full Text Search

estimateQueryCost({ rows, joins, indexes }) is a toy model, not a real database cost. Start from rows, multiply by 1.5 for each join, divide by 10 once if there is an index (indexes > 0, however many), then Math.round.

Plan Working Result
{ rows: 1000, joins: 2, indexes: 1 } 1000 × 1.5 × 1.5 ÷ 10 225
{ rows: 100, joins: 0, indexes: 0 } 100 100
{ rows: 500, joins: 1, indexes: 2 } 500 × 1.5 ÷ 10 75

⚠️ Unused indexes and hidden queries

TL;DR: Every query (a command to the database) costs a round trip. N+1 is 1 query for the list + 1 query per row: 20 posts become 21 queries, and the cost adds up fast. Eager loading (loading related data all at once, with('author') in Laravel) makes it always 2 queries. A B-tree index (a sorted structure, like a library catalogue) lets the database find rows straight through the columns in WHERE, JOIN and ORDER BY, instead of by full scan (reading every row). But every index makes writing data slower. Check a query's plan with EXPLAIN (type: ALL, key: NULL means a full scan) or EXPLAIN ANALYZE for real times. Select only the columns you need, avoid functions on columns and LIKE '%...', use cursor pagination (continuing from the last row) for far pages, and cache frequent reads.

⚡ N+1 queries

Write:

$posts = Post::with('author')->latest()->take(20)->get();
Guess first: a page shows 20 posts with their authors' names, and each post's author is loaded one at a time inside a loop. How many queries (commands to the database) run?

21 queries: one for the list of posts, then one more for each post's author. This pattern is called N+1. With with('author') (eager loading: loading all the authors at once), it's always 2 queries, whether there are 20 posts or 100.

Meaning: Every query costs a round trip to the database, so small queries inside a loop add up fast. The code above gets the 20 newest posts with each one's author in only 2 queries.

⚡ An index is a sorted catalogue

Write:

CREATE INDEX idx_posts_created_at ON posts (created_at);

Meaning: An index is an extra structure, like a library's sorted catalogue, that lets the database go straight to the rows it's looking for. This command creates an index on the created_at column of the posts table. Without an index, the database reads every row (a full scan). In the Lab, the query for the 20 newest posts drops from about 45 ms to about 1 ms. Index only the columns used in WHERE, JOIN and ORDER BY (filtering, combining, sorting), because every index makes writing data slower.

⚡ Ask the database for its plan

Meaning: To see a query's execution plan (how the database plans to run the query), use EXPLAIN, or EXPLAIN ANALYZE for real times. In the EXPLAIN result, type: ALL and key: NULL mean a full scan. A function on the column, such as YEAR(created_at), and LIKE '%...' (searching for part of a text) leave the index unused.

What you will learn