Skip to content

Module 07 · Lesson 7.3

Database and Query Problems

45 minUpdated 19 Nov 2026Part of Performance and Reliability Investigation · Existing Project Engineering
On this page
  1. What you will learn
  2. N+1 queries, indexes and query plans in plain words
  3. Fix 1: fetch the lines and products together
  4. Fix 2: a missing index, confirmed with a real query plan
  5. What an index costs, and how to test it on real data
  6. Step-by-step workflow
  7. Using an AI assistant for query problems
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

Think of a library. If you want one author's books, you can walk past every shelf and check each spine. Or you can use the card index, which tells you the shelf at once. The books are the same. The way you look is different, and so is the time it takes.

A database works the same way. In this lesson you will fix the two problems behind the slow "My orders" page of the fictional Tidewell Wholesale service: too many queries, and a missing index. You will check both with evidence, including a real PostgreSQL query plan. The code is simplified so you can run it, and all data is invented.

What you will learn

  • Replace an N+1 pattern with a fixed number of queries and show the count.
  • Explain what an index is and when a query needs one.
  • Read a PostgreSQL EXPLAIN plan before and after adding an index.
  • State the cost of an index and how to test a change on realistic data.

Before you start

  • You finished Profiling and Reading the Evidence, and you have the files seed.py, history_slow.py and query_counter.py from it.
  • You can run short Python scripts, and you have read a simple SQL query.
  • Node.js is optional. The lesson shows real PostgreSQL output, so you do not need to run it.

N+1 queries, indexes and query plans in plain words

Two things made the page slow, and they are different problems. One is about how many questions the code asks. The other is about how the database finds the answer to one question.

N+1 query pattern
One query for a list, then one more query for each item in it. You met it in the last lesson: 1 + 50 + 150 = 201 queries. Like walking to the shop 201 times for things you could carry home in two trips.
Join
A way to ask the database for rows from two tables at once, matched by a shared value. For example, each order line together with its product's name.
Index
A sorted lookup list the database keeps beside a table, so it can jump to the rows it needs. It is the index at the back of a book: you do not read every page to find 'napkins'.
Sequential scan (Seq Scan)
The database reads every row of the table, one after another, and keeps the ones that match. Like checking every spine on every shelf.
Query plan
The database's own description of how it will answer a query, step by step. You ask for it with the word EXPLAIN. It is the route a satnav shows before you set off.

Fix the first problem first. It is the bigger one, it is easy to count, and it needs no database change. Then deal with the plan.

Fix 1: fetch the lines and products together

The idea is simple. Instead of asking for each order's lines one at a time, ask once for the lines of all 50 orders. Join the products in the same query, so no second trip is needed. That makes two queries: one for the orders, one for lines with their product names.

Pythonhistory_fast.py
def order_history(conn, customer_id, limit=50):
    orders = conn.execute(
        "SELECT id, created_at FROM orders "
        "WHERE customer_id = ? ORDER BY created_at DESC LIMIT ?",
        (customer_id, limit),
    ).fetchall()
    if not orders:
        return []  # an empty IN () list is not valid SQL in PostgreSQL

    ids = [order_id for order_id, _ in orders]
    marks = ", ".join("?" for _ in ids)  # only question marks, never user text
    rows = conn.execute(
        "SELECT l.order_id, p.name, l.qty, l.unit_price_pence "
        "FROM order_lines l JOIN products p ON p.id = l.product_id "
        "WHERE l.order_id IN (" + marks + ") ORDER BY l.id",
        ids,
    ).fetchall()

    lines_by_order = {order_id: [] for order_id in ids}
    for order_id, name, qty, price in rows:
        lines_by_order[order_id].append(
            {"product": name, "qty": qty, "line_total_pence": qty * price}
        )

    return [
        {"order_id": order_id, "created_at": created_at,
         "lines": lines_by_order[order_id],
         "total_pence": sum(l["line_total_pence"] for l in lines_by_order[order_id])}
        for order_id, created_at in orders
    ]

The same order_history, with two queries. It returns the same data in the same shape.

What each part does

  • The first query is unchanged: the latest orders for this account.
  • if not orders: return [] handles an account with no orders. An empty IN () list is not valid SQL in PostgreSQL, so we stop early.
  • marks builds the text ?, ?, ?, ..., one question mark per order id. The ids themselves travel separately as parameters. Only question marks are added to the SQL text, never user input.
  • The second query joins order_lines to products and fetches the lines of every order at once. ORDER BY l.id keeps the lines in the same order as before.
  • lines_by_order groups the rows by order in Python, in one pass.
  • The last list builds the same dictionaries as the slow version.
Pythonfast_demo.py
import history_fast
import history_slow
from query_counter import QueryCounter
from seed import seeded_connection

conn = seeded_connection()
results = {}
for label, module in (("slow", history_slow), ("fast", history_fast)):
    with QueryCounter(conn) as counter:
        results[label] = module.order_history(conn, "TC7-0042", limit=50)
    print(f"{label}: {counter.count} queries, {len(results[label])} orders")

print("same output:", results["slow"] == results["fast"])

Counts the queries of both versions and compares their output.

Real output (run twice, identical)Captured from a real run
slow: 201 queries, 50 orders
fast: 2 queries, 50 orders
same output: True

201 queries became 2, and the two versions return exactly the same data. Do not skip that last line. A fast answer that is different is a bug, not an improvement. The next lesson turns that check into a proper test.

In Django

Django has a name for this idea: it can load related rows ahead of time. Here are two excerpts for the real service. They are not runnable on their own, and the counts depend on your models.

Pythonorders/selectors.py (excerpt)
from django.db.models import Prefetch

# Short form: Django runs one query each for orders, lines and products (3).
orders = (Order.objects.filter(customer_id=customer_id)
          .order_by("-created_at")
          .prefetch_related("lines__product"))[:limit]

# Two queries: the product is joined into the lines query.
orders = (Order.objects.filter(customer_id=customer_id)
          .order_by("-created_at")
          .prefetch_related(Prefetch(
              "lines", queryset=OrderLine.objects.select_related("product")))
          )[:limit]

Two ways to load lines and products ahead of time in Django.

prefetch_related fetches related rows in a separate query and joins them up in Python. select_related joins a single related row into the same query. The short form is 3 queries and the second is 2. Both are far fewer than 201. Whichever you choose, count again with your query counter or assertNumQueries. Read the Django page on database access optimization (opens in a new tab) and the QuerySet reference (opens in a new tab) for the details.

Fix 2: a missing index, confirmed with a real query plan

Now look at the first query on its own. It asks for one account's orders, sorted newest first, and keeps the top 50. In the real service this table is in PostgreSQL and holds all customers' orders. The query filters on customer_id and sorts on created_at, and the table has no index that helps.

You cannot see that from the code. You ask the database. To do so with real PostgreSQL, this lesson uses PGlite, which runs PostgreSQL inside a Node.js program. You will only see the SQL and its output, not the harness. First, the practice table: 20,000 orders for 200 accounts, where TC7-0042 is the big one with 1,818 orders. The numbers are made up with a formula, so the output never changes.

SQLsetup.sql
CREATE TABLE orders (
    id          integer PRIMARY KEY,
    customer_id text NOT NULL,
    created_at  timestamp NOT NULL,
    total_pence integer NOT NULL
);

-- 20,000 orders for 200 accounts. TC7-0042 is the big one (1,818 orders).
INSERT INTO orders (id, customer_id, created_at, total_pence)
SELECT n,
       'TC7-' || CASE WHEN n % 11 = 0 THEN '0042'
                      ELSE (1000 + n % 199)::text END,
       timestamp '2024-01-01' + (n * interval '37 minutes'),
       1000 + (n * 7919) % 90000
FROM generate_series(1, 20000) AS n;

ANALYZE orders;

Creates and fills the table, then runs ANALYZE so the planner has statistics about the data.

ANALYZE makes PostgreSQL look at the data and record how it is spread out. The planner uses this to choose a plan. Without it, plans on a fresh table can be misleading. Now ask for the plan. Costs are switched off so the output stays short and steady.

SQLexplain_before.sql
EXPLAIN (COSTS OFF)
SELECT id, created_at, total_pence
FROM orders
WHERE customer_id = 'TC7-0042'
ORDER BY created_at DESC
LIMIT 50;

Asks PostgreSQL how it would run the orders query. EXPLAIN does not run the query itself.

Real PostgreSQL plan, before the index (run twice, identical; PGlite, PostgreSQL 18)Captured from a real run
Limit
  ->  Sort
        Sort Key: created_at DESC
        ->  Seq Scan on orders
              Filter: (customer_id = 'TC7-0042'::text)

Read a plan from the inside out. The deepest step runs first. Here: Seq Scan on orders, keeping rows where the customer matches. Then Sort them by date, newest first. Then Limit to the first 50. In other words: read the whole table, keep this account's rows, sort them all, and throw most of them away.

To see how much work that is, ask for EXPLAIN ANALYZE. Unlike plain EXPLAIN, it runs the query and reports what really happened. Timing is turned off so the output stays the same on every machine.

SQLexplain_analyze.sql
EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, created_at, total_pence
FROM orders
WHERE customer_id = 'TC7-0042'
ORDER BY created_at DESC
LIMIT 50;

Runs the query and reports actual row counts. BUFFERS, TIMING and SUMMARY are off so the output is repeatable.

Real output, before the index (run twice, identical)Captured from a real run
Limit (actual rows=50.00 loops=1)
  ->  Sort (actual rows=50.00 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 24kB
        ->  Seq Scan on orders (actual rows=1818.00 loops=1)
              Filter: (customer_id = 'TC7-0042'::text)
              Rows Removed by Filter: 18182

Look at Rows Removed by Filter: 18182. The database looked at all 20,000 rows and threw 18,182 away. That is the waste, and it grows with the table. Now add an index that matches the query: first the column we filter on, then the column we sort on.

SQLcreate_index.sql
CREATE INDEX orders_customer_created_idx
    ON orders (customer_id, created_at DESC);

ANALYZE orders;

An index on account, then date from newest to oldest.

The order of the columns matters. The index is sorted by customer_id first, and inside each customer by created_at. That is exactly what the query asks for, so the database can go to TC7-0042 and read orders off the list in date order. See the PostgreSQL page on multicolumn indexes (opens in a new tab). Now run the same two EXPLAIN statements again.

Real PostgreSQL plan, after the index (run twice, identical)Captured from a real run
Limit
  ->  Index Scan using orders_customer_created_idx on orders
        Index Cond: (customer_id = 'TC7-0042'::text)
Real EXPLAIN ANALYZE output, after the index (run twice, identical)Captured from a real run
Limit (actual rows=50.00 loops=1)
  ->  Index Scan using orders_customer_created_idx on orders (actual rows=50.00 loops=1)
        Index Cond: (customer_id = 'TC7-0042'::text)
        Index Searches: 1

The plan changed shape. The Seq Scan and the Sort are gone. One Index Scan reads the account's entries in order and stops after 50 rows. No rows are removed, and nothing is sorted. The word 'Index Searches' is printed by newer PostgreSQL versions, so your output may differ a little.

Plan wordPlain meaning
Seq ScanRead every row of the table.
Filter / Rows Removed by FilterA test applied to each row, and how many rows failed it. A big number means wasted reading.
SortPut the rows in order. Costs extra when there are many rows.
LimitStop after this many rows.
Index ScanUse an index to jump to the matching rows, often in the right order.
Index CondThe condition the index handled.
actual rowsHow many rows that step really produced (shown by EXPLAIN ANALYZE).
The plan words you need for this lesson.

What an index costs, and how to test it on real data

An index is not free. Think of the index at the back of a book. Someone has to keep it up to date every time a page changes.

  • Slower writes. Every new order must also be added to the index. One more index means a little more work on each insert and update.
  • More disk space. The index is stored in addition to the table.
  • Maintenance. Indexes that no query uses are clutter. Add the ones you can justify.
  • Locking. Building an index on a big live table can block writes. PostgreSQL has a CREATE INDEX CONCURRENTLY option for this. Check the documentation, and agree the timing with your platform team lead.

For orders, one extra index is a sensible price. Orders are written a few at a time and read many times. A table with thousands of writes per second would need more thought.

The plan from a synthetic table is a good sign, but it is not proof for your real data. The real test is EXPLAIN ANALYZE on a copy of production data, which has the real spread of customers and order dates. Make sure the copy is anonymised and that you have permission to use it. See Sharing Code with an AI Assistant Safely. Read the PostgreSQL guide to using EXPLAIN (opens in a new tab) for more.

Other heavy reads to look for

ProblemPlain pictureWhat to look for
Too many columnsCarrying the whole filing cabinet to read one pageSELECT * when you need three fields. Ask only for what you use.
No limitAsking for every order ever placedQueries on big tables without LIMIT or paging.
Filtering in PythonFetching all rows, then sorting them at your deskA big fetch followed by a loop that discards most rows.
Repeated identical queriesAsking the same question again and againThe same query shape called many times in one request.
Four more things that make reads heavy. Count and measure each before fixing it.

Step-by-step workflow

  1. Step 1: Start from the evidence

    Take the query count and the slow query from the last lesson. Decide which problem you are fixing first: too many queries, or one slow query.

    What you should see: One problem, one measurement to improve.

  2. Step 2: Fix the number of queries

    Load related rows together, with a join or your framework's prefetch. Keep the function's output exactly the same.

    What you should see: A lower query count with the same output.

  3. Step 3: Re-count and compare

    Run the query counter again, and compare the old and new output. Both must agree.

    What you should see: 201 becomes 2, and 'same output: True'.

  4. Step 4: Ask the database for the plan

    Run EXPLAIN on the slow query against realistic data, after ANALYZE. Look for Seq Scan, Sort and Rows Removed by Filter.

    What you should see: A plan you can describe in two sentences.

  5. Step 5: Add the smallest index that fits

    Match the query: equality columns first, then the sort column. Add it in a migration that can be rolled back. Think about its write cost.

    What you should see: A reviewed migration with an index.

  6. Step 6: Check the plan again, on a production-like copy

    Run EXPLAIN and EXPLAIN ANALYZE again. The plan should now use the index. Then repeat on the anonymised copy, because that is the real test.

    What you should see: Before and after plans, saved in your notes.

From repeated queries to a checked index
  1. Evidence

    201 queries, slow query

  2. Load together

    Join or prefetch

  3. Re-count

    201 to 2, same output

  4. EXPLAIN

    Seq Scan, Sort

  5. Add index

    Customer, then date

  6. EXPLAIN again

    Index Scan, on real-like data

Fix the count first. Then look at the single slow query and its plan.

Using an AI assistant for query problems

An assistant can explain a query plan in words and suggest an index. It is useful here, because plans are dense and the vocabulary is new. It cannot see your data or your server, so its suggestion is a hypothesis to test.

  • Give it: the query, the table definition, and the EXPLAIN output before the change. Remove real values, and use account codes, not names.
  • Ask it for: a plain-words reading of the plan, the cause of the waste, and one proposed index with its trade-offs.
  • Watch for: an index with the columns in the wrong order, a separate index per column (which still leaves a sort), or an index on a column that is rarely used in queries.
  • Then test: run EXPLAIN again with its index and see whether the plan changes the way it said.

Conclusion and your next step

You fixed two separate problems with evidence. You cut 201 queries to 2 without changing the output. You also read a real PostgreSQL plan, saw a Seq Scan and a Sort replaced by an Index Scan, and learned what an index costs.

Your next step: not every slow system is slow because of its own queries. Continue with Failure Modes, Timeouts and Retries and see what happens when a partner's system is slow or down.

For more, read Load Testing with AI: Generating Realistic Performance Test Scenarios and the module overview Performance and Reliability Investigation.

Reusable prompt

Query plan reader and index review

Asks an assistant to explain a query plan in plain words, name the waste, and propose one index with its trade-offs and a test, using only the evidence you give.

I am reviewing a slow query in a PostgreSQL database behind a Django service called tidewell-orders (fictional). Use ONLY the evidence below. Do not invent row counts or timings.

Query:
SELECT id, created_at, total_pence
FROM orders
WHERE customer_id = 'TC7-0042'
ORDER BY created_at DESC
LIMIT 50;

Table (simplified): orders(id integer primary key, customer_id text, created_at timestamp, total_pence integer). About 20,000 rows in my test copy; account TC7-0042 has 1,818 orders. ANALYZE was run.

EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF) output:
Limit (actual rows=50.00 loops=1)
  ->  Sort (actual rows=50.00 loops=1)
        Sort Key: created_at DESC
        Sort Method: top-N heapsort  Memory: 24kB
        ->  Seq Scan on orders (actual rows=1818.00 loops=1)
              Filter: (customer_id = 'TC7-0042'::text)
              Rows Removed by Filter: 18182

Please give me:
1. A plain-words reading of the plan, step by step, for a beginner.
2. The main waste you can see in the plan, and the line that shows it.
3. ONE proposed index, with the column order explained.
4. The trade-offs of that index, including write cost.
5. How I should check that it worked, and what I should test on a production-like copy.
Mark any guess as (unverified).
Show the reusable template

Replace each {{placeholder}} with your own details.

I am reviewing a slow query in {{database_and_service}}. Use ONLY the evidence below. Do not invent row counts or timings.

Query:
{{query}}

Table (simplified): {{table_definition_and_row_counts}}. ANALYZE was run: {{yes_or_no}}.

EXPLAIN output:
{{explain_output}}

Please give me:
1. A plain-words reading of the plan, step by step, for a beginner.
2. The main waste you can see in the plan, and the line that shows it.
3. ONE proposed index, with the column order explained.
4. The trade-offs of that index, including write cost.
5. How I should check that it worked, and what I should test on a production-like copy.
Mark any guess as (unverified).

Expected output and limitations

A step-by-step reading of the plan, the line that shows the waste, one proposed index with the column order explained, its costs and a way to check. It should refer to your numbers and should not invent others.

Sample responseIllustrative — your output will differ
1. Reading the plan, from the inside out
- Seq Scan on orders: the database read every row.
- Filter: it kept only rows for TC7-0042 (1,818 rows).
- Sort by created_at DESC: it sorted those 1,818 rows.
- Limit: it returned the first 50.

2. The waste
"Rows Removed by Filter: 18182": most of the table was read and thrown away.

3. Proposed index
CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at DESC);
customer_id comes first because the query tests it for equality. created_at DESC comes second so the rows can be read already in the order the query wants, without a sort.

4. Trade-offs
- Every insert and update on orders also updates the index (slower writes).
- Extra disk space.
- (unverified) The planner may still choose another plan on a very small table.

5. How to check
Run EXPLAIN again after the index exists. You expect an Index Scan and no Sort. Then run EXPLAIN ANALYZE on a production-like copy.

Limitations to keep in mind

  • The assistant has only your pasted plan. It cannot know how your real data is spread.
  • It may propose several indexes, or one per column. One index that matches the query is usually the better start, and you should test it.
  • It may predict timings. Ignore them. Only your own measurements count.
  • It cannot tell you what the extra index costs your write traffic. That needs your numbers.

Common errors and how to fix them

Fixing the index before the query count

Why it happens: Indexes sound like the classic database fix, so people start there.

Fix: Count the queries first. 201 round trips cost more than one slow scan, and no index removes them.

Reading the plan from the top

Why it happens: Plans print the last step first, which makes the top line look like the first thing that happens.

Fix: Read from the deepest line outwards. The deepest step runs first, and the top line is the final result.

Trusting a plan from a tiny or unanalysed table

Why it happens: Small data or missing statistics make the planner choose differently from production.

Fix: Use realistic row counts, run ANALYZE, and repeat the check on a production-like copy before you rely on it.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Find one repeated query and one missing index in your own repository

In a repository or sample application you may study, find a request that runs a query inside a loop, and a query whose plan shows a sequential scan. Fix one, and record the evidence.

You will need

  • A repository you may run, with a test database that has realistic row counts.
  • A query counter for your stack, and access to EXPLAIN for your database.
  • The evidence note from the previous lesson.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If you use another database, the keyword may be EXPLAIN, EXPLAIN QUERY PLAN or a graphical plan. The idea is the same.
  • If the plan does not change after your index, check the column order and that statistics are fresh.
  • If you ask an assistant, give it the plan and the table, and ask for one index with trade-offs.
Show a model answer

A strong answer shows a count such as 201 to 2 with the output compared, and two plans with the changed lines explained: Seq Scan and Sort before, Index Scan after. It names the index and its column order and gives a reason. It says plainly what an extra index costs and that production-like data was or was not tested. A weak answer adds an index with no plan, or says 'it feels faster'.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A query plan shows a Seq Scan with 'Rows Removed by Filter: 18182' and only 1,818 rows kept. What does it tell you?
    Show the answer and explanation

    Answer: A. Rows removed by the filter are rows read and discarded, so the waste is visible. It is not damage, and the query returned only the rows that passed the filter. An index can let the database skip the rest.

  2. 2.You create an index on (created_at, customer_id) for a query that filters on customer_id and sorts on created_at. Why might it be the wrong order?
    Show the answer and explanation

    Answer: B. An index sorted by date first mixes all accounts together, so jumping to one account does not work well. Put the column tested for equality first, then the sort column. Dates can be indexed, and the order of columns is a design choice.

  3. 3.Your new index fixes the plan on a test table. What is the best next step before release?
    Show the answer and explanation

    Answer: B. A toy table can plan differently from production, and an index slows writes. Checking on realistic data is the real test. More indexes add more cost without evidence.

Frequently asked questions

What does EXPLAIN do in a database?

EXPLAIN shows the plan the database would use to answer a query, without running it. EXPLAIN ANALYZE runs the query and reports what really happened, such as how many rows each step produced. You read the plan to see where the work goes.

What is a database index, in simple terms?

An index is a sorted lookup list kept beside a table. It lets the database jump to the rows it needs instead of reading everything. It speeds up reads and slows down writes a little, because the list must be updated.

Does adding an index always make a query faster?

No. If the index does not match the query, the planner may ignore it, and you pay the write cost for nothing. On a small table, a full scan can be just as fast. Check the plan and measure before and after.

How do I know if my code has an N+1 problem?

Count the queries for one request, with a small input and a larger one. If the count grows with the size of the list, it is likely an N+1 pattern. Django tools such as assertNumQueries and django-debug-toolbar make this easy to see.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.