Database Indexes and Performance · Lesson 56 of 112

Database Speed-up Tips

What you will learn

  • Select only what you need
  • Spot and fix the N+1 query pattern
  • Batch many writes in one transaction
  • Page through results with keyset pagination
  • Measure before and after

Setup. These are the same helpers as in lesson 7.1 (build(), plan(), timeit()), copied here so this page runs on its own:

import sqlite3
import time

CITIES = ["Dhaka", "Khulna", "Sylhet", "Rajshahi", "Barishal", "Chattogram", "Rangpur", "Mymensingh"]

def build(n=100000):
    con = sqlite3.connect(":memory:")
    con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, city TEXT, status TEXT, amount INTEGER, placed TEXT)")
    rows = []
    for i in range(1, n + 1):
        cust = (i * 7919) % 5000 + 1
        rows.append((i, cust, CITIES[cust % 8], "shipped" if i % 10 else "pending", (i * 37) % 1000,
                     "2026-%02d-%02d" % (i % 12 + 1, i % 28 + 1)))
    con.executemany("INSERT INTO orders VALUES (?,?,?,?,?,?)", rows)
    con.commit()
    return con

def plan(con, sql, args=()):
    for r in con.execute("EXPLAIN QUERY PLAN " + sql, args):
        print(r[3])

def timeit(con, sql, args=(), reps=20):
    t = time.perf_counter()
    for _ in range(reps):
        con.execute(sql, args).fetchall()
    return (time.perf_counter() - t) / reps * 1000

Indexes are one tool. These habits help just as much. The examples use a smaller orders table (20,000 rows, built with the build() helper from the Setup block above) and a customers table:

con = build(20000)
con.execute("CREATE INDEX idx_c ON orders (customer_id)")
con.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT)")
con.executemany("INSERT INTO customers VALUES (?,?)", [(i, "C%d" % i) for i in range(1, 5001)])

1. Ask only for what you need

SELECT * fetches every column, even ones you will not use. Wide rows and big results cost time to read and to send over a network.

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Indexes you create live in your browser's copy; Reset data removes them. For EXPLAIN QUERY PLAN the cell shows only the plan text.

SELECT * FROM orders LIMIT 1;
SELECT order_id, status FROM orders LIMIT 1;
order_id  customer_id  employee_id  order_date  status     shipped_on  ship_city
--------  -----------  -----------  ----------  ---------  ----------  ---------
       1          279            4  2025-04-23  delivered  2025-04-24  Dhaka
(1 row)

order_id  status
--------  ---------
       1  delivered
(1 row)
SELECT * FROM transactions LIMIT 1;
SELECT txn_id, amount_cents FROM transactions LIMIT 1;
txn_id  account_id  txn_date    kind     amount_cents  balance_after  description
------  ----------  ----------  -------  ------------  -------------  ---------------
     1         154  2018-02-23  deposit         54800          54800  Opening deposit
(1 row)

txn_id  amount_cents
------  ------------
     1         54800
(1 row)
SELECT * FROM students LIMIT 1;
SELECT student_id, last_name FROM students LIMIT 1;
student_id  first_name  last_name  birth_date  enrolled_year  email                        guardian_name
----------  ----------  ---------  ----------  -------------  ---------------------------  -------------
         1  Vera        Khan       2012-04-28           2026  vera.khan38@student.example  Amir Khan
(1 row)

student_id  last_name
----------  ---------
         1  Khan
(1 row)

Name the columns your code needs, and use LIMIT when you need only a few rows. It also lets a covering index (lesson 7.5) do the work.

2. The N+1 pattern

"For each customer, how many orders?" A common mistake is one query for the customers, then one more query per customer: 1 + 300 = 301 queries for 300 customers. One join with GROUP BY does it in a single query:

SELECT c.customer_id, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE c.customer_id <= 5
GROUP BY c.customer_id
ORDER BY c.customer_id;
customer_id  orders
-----------  ------
          1       9
          2       6
          3       6
          4       5
          5      10
(5 rows)
SELECT c.customer_id, COUNT(a.account_id) AS accounts
FROM customers c
LEFT JOIN accounts a ON a.customer_id = c.customer_id
WHERE c.customer_id <= 5
GROUP BY c.customer_id
ORDER BY c.customer_id;
customer_id  accounts
-----------  --------
          1         1
          2         0
          3         2
          4         0
          5         2
(5 rows)
SELECT t.teacher_id, COUNT(s.section_id) AS sections
FROM teachers t
LEFT JOIN sections s ON s.teacher_id = t.teacher_id
WHERE t.teacher_id <= 5
GROUP BY t.teacher_id
ORDER BY t.teacher_id;
teacher_id  sections
----------  --------
         1         2
         2         1
         3         1
         4         2
         5         0
(5 rows)

The loop version is application code, so it is shown in Python:

import sqlite3, time

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY)")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER)")
con.executemany("INSERT INTO customers VALUES (?)", [(i,) for i in range(1, 301)])
con.executemany("INSERT INTO orders (customer_id) VALUES (?)", [(i % 300 + 1,) for i in range(3000)])
t = time.perf_counter(); n = 0
for (cid,) in con.execute("SELECT id FROM customers").fetchall():
    con.execute("SELECT COUNT(*) FROM orders WHERE customer_id = ?", (cid,)).fetchone(); n += 1
print("N+1: %d queries, %.1f ms" % (n + 1, (time.perf_counter() - t) * 1000))
t = time.perf_counter()
r = con.execute("SELECT c.id, COUNT(o.id) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.id").fetchall()
print("one JOIN: 1 query, %.1f ms, %d rows" % ((time.perf_counter() - t) * 1000, len(r)))

Here the difference is small because SQLite runs inside the program with no network. With a database on another machine, every query is a separate trip between the two computers, so 301 queries would be expected to cost much more than one. That is reasoning, not a measurement from this lesson; test it on your own setup. In any case the join is shorter and lets the database plan the whole job.

3. Batch your writes

Each COMMIT makes the database save changes safely to disk (chapter 6). Committing after every row repeats that work:

import os, tempfile
def ins(per_row):
    path = os.path.join(tempfile.mkdtemp(), "b.db")
    c = sqlite3.connect(path); c.execute("CREATE TABLE t (a INTEGER, b TEXT)"); c.commit()
    t = time.perf_counter()
    if per_row:
        for i in range(300):
            c.execute("INSERT INTO t VALUES (?, 'x')", (i,)); c.commit()
    else:
        c.executemany("INSERT INTO t VALUES (?, 'x')", [(i,) for i in range(300)]); c.commit()
    ms = (time.perf_counter()-t)*1000; c.close(); return ms
print("300 inserts, commit each: %.0f ms; one batch: %.1f ms" % (ins(True), ins(False)))
300 inserts, commit each: 1624 ms; one batch: 7.0 ms

On this machine, 300 inserts with a commit each took 1,624 ms; the same inserts in one batch took 7 ms. (The gap depends on the disk.) Group related writes in one transaction.

4. Paging without a big OFFSET

For "page 500 of the results", a big OFFSET makes the database walk past all the earlier rows before returning three. Keyset pagination remembers the last id seen and asks for the rows after it:

SELECT order_id FROM orders ORDER BY order_id LIMIT 3 OFFSET 1500;
SELECT order_id FROM orders WHERE order_id > 1500 ORDER BY order_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT order_id FROM orders WHERE order_id > 1500 ORDER BY order_id LIMIT 3;
order_id
--------
    1501
    1502
    1503
(3 rows)

order_id
--------
    1501
    1502
    1503
(3 rows)

plan
-------------------------------------------------
SEARCH orders USING INTEGER PRIMARY KEY (rowid>?)
(1 row)
SELECT txn_id FROM transactions ORDER BY txn_id LIMIT 3 OFFSET 5000;
SELECT txn_id FROM transactions WHERE txn_id > 5000 ORDER BY txn_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT txn_id FROM transactions WHERE txn_id > 5000 ORDER BY txn_id LIMIT 3;
txn_id
------
  5001
  5002
  5003
(3 rows)

txn_id
------
  5001
  5002
  5003
(3 rows)

plan
-------------------------------------------------------
SEARCH transactions USING INTEGER PRIMARY KEY (rowid>?)
(1 row)
SELECT student_id FROM students ORDER BY student_id LIMIT 3 OFFSET 300;
SELECT student_id FROM students WHERE student_id > 300 ORDER BY student_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT student_id FROM students WHERE student_id > 300 ORDER BY student_id LIMIT 3;
student_id
----------
       301
       302
       303
(3 rows)

student_id
----------
       301
       302
       303
(3 rows)

plan
---------------------------------------------------
SEARCH students USING INTEGER PRIMARY KEY (rowid>?)
(1 row)

Same three rows; the keyset form jumps to the first id after the last one seen through the primary key, while OFFSET has to count its way there, and the gap tends to widen with deeper pages. The trade-off: it needs a unique, ordered column, and it gives "next page" more naturally than "jump to page 500". If you sort by a column that is not unique, such as a date, add the unique id as a tie-break so no row is skipped or repeated: remember the last (date, id) pair and ask for the rows after it. SQLite and several other databases allow comparing pairs directly:

CREATE INDEX idx_orders_date_id ON orders (order_date, order_id);
SELECT order_id, order_date FROM orders WHERE (order_date, order_id) > ('2025-03-05', 50) ORDER BY order_date, order_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT order_id, order_date FROM orders WHERE (order_date, order_id) > ('2025-03-05', 50) ORDER BY order_date, order_id LIMIT 3;
order_id  order_date
--------  ----------
     232  2025-03-05
     396  2025-03-05
     423  2025-03-05
(3 rows)

plan
--------------------------------------------------------------------
SEARCH orders USING COVERING INDEX idx_orders_date_id (order_date>?)
(1 row)
CREATE INDEX idx_txn_date_id ON transactions (txn_date, txn_id);
SELECT txn_id, txn_date FROM transactions WHERE (txn_date, txn_id) > ('2025-03-05', 50) ORDER BY txn_date, txn_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT txn_id, txn_date FROM transactions WHERE (txn_date, txn_id) > ('2025-03-05', 50) ORDER BY txn_date, txn_id LIMIT 3;
txn_id  txn_date
------  ----------
  4344  2025-03-05
  4345  2025-03-05
  4346  2025-03-05
(3 rows)

plan
---------------------------------------------------------------------
SEARCH transactions USING COVERING INDEX idx_txn_date_id (txn_date>?)
(1 row)
CREATE INDEX idx_students_birth_id ON students (birth_date, student_id);
SELECT student_id, birth_date FROM students WHERE (birth_date, student_id) > ('2012-06-01', 50) ORDER BY birth_date, student_id LIMIT 3;
EXPLAIN QUERY PLAN SELECT student_id, birth_date FROM students WHERE (birth_date, student_id) > ('2012-06-01', 50) ORDER BY birth_date, student_id LIMIT 3;
student_id  birth_date
----------  ----------
        58  2012-06-03
        69  2012-06-04
       109  2012-06-04
(3 rows)

plan
-------------------------------------------------------------------------
SEARCH students USING COVERING INDEX idx_students_birth_id (birth_date>?)
(1 row)

The composite index (lesson 7.5) lets the database jump straight to the place after the last page.

Worked example: tuning a slow report page

A report lists orders, 20 per page, with the customer's name, and gets slower on later pages. A short plan:

  1. Measure: how long does the page take, and how many queries does it run?
  2. If it runs one query per row for the name, replace it with a JOIN (N+1).
  3. Select only the columns shown.
  4. Check the plan: is the ORDER BY column indexed?
  5. Replace a deep OFFSET with keyset paging.
  6. Measure again and keep only the changes that helped.

The report is made up.

Caching and other tools. Keeping the answers to repeated questions in memory (a cache) can help further, and databases offer more tools such as statistics updates (ANALYZE in SQLite) and views. They are not tried in this lesson; read your database's documentation and use them after the simple steps above.

Common mistakes

  • Using SELECT * everywhere.
  • Running a query inside a loop when one join would do.
  • Committing after every single row of a big import.
  • Using huge OFFSET values for deep pages.
  • Optimising without measuring. Change one thing at a time and time it.

Key takeaways

  • Select only the columns and rows you need.
  • Avoid N+1: use a join or one query for the whole set.
  • Batch writes in one transaction instead of committing per row (1,624 ms vs 7 ms in our test).
  • Keyset pagination beats deep OFFSET.
  • Measure before and after every change.

Practice

1. What is the N+1 pattern?

Show answer

One query to get a list, then one more query for each item in it (1 + N queries), when a single join could do it.

2. Why can N+1 hurt more when the database is on another computer?

Show answer

Each query is a separate trip over the network, so many small queries add up.

3. Why was one batch faster than 300 separate commits?

Show answer

Each commit makes the database save safely to disk, so 300 commits repeat that work 300 times.

4. Rewrite ... ORDER BY id LIMIT 20 OFFSET 400 as keyset paging, given the last id seen is 400. Then explain what extra column you would need if the list were sorted by placed instead.

Show answer

SELECT ... WHERE id > 400 ORDER BY id LIMIT 20. For ORDER BY placed, add id as a tie-break: WHERE (placed, id) > (?, ?) ORDER BY placed, id, because many rows can share the same placed value.

5. Why select only needed columns?

Show answer

Less data is read and sent, and a covering index may then answer the query alone.

6. What should you do before and after changing a query for speed?

Show answer

Measure it (and read its plan), then measure again to confirm the change helped.