Reading history

SQL Query Optimization: Query Plans and Index-Friendly Queries

6 min read 0 views

Speed up slow SQL queries: read EXPLAIN QUERY PLAN, write sargable conditions, order composite indexes, use covering indexes and avoid common traps.

A query that takes 2 milliseconds on 100 test rows can take 20 seconds on 10 million real ones. Most slow queries are not fixed by faster servers but by small changes in how the query is written and which indexes exist. This lesson shows how to read a query plan and the handful of rules that fix most slow queries: keep columns “bare” in WHERE, order composite indexes well, and let an index cover the whole query.

In this lesson you will learn

  • Reading EXPLAIN QUERY PLAN: SCAN versus SEARCH
  • Why a function on a column stops the index being used
  • Rewriting conditions as ranges
  • Column order in composite indexes
  • Covering indexes and other quick wins

You should know how to create indexes and use date functions. Each example fills a payments table with 50,000 rows so the plans are realistic.

Keep the Column Bare

-- 50,000 sample payments
CREATE TABLE payments (id INTEGER PRIMARY KEY, customer_id INTEGER, paid_on TEXT, amount INTEGER, method TEXT);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 50000)
INSERT INTO payments (customer_id, paid_on, amount, method)
SELECT i % 2000, date('2025-01-01', '+' || (i % 365) || ' days'), (i * 37) % 5000,
       CASE i % 3 WHEN 0 THEN 'bkash' WHEN 1 THEN 'card' ELSE 'cash' END
FROM n;
CREATE INDEX idx_paid_on ON payments(paid_on);

-- 1. A function on the column hides it from the index
EXPLAIN QUERY PLAN
SELECT SUM(amount) FROM payments WHERE strftime('%Y-%m', paid_on) = '2025-03';

-- 2. Same question, written as a range on the bare column
EXPLAIN QUERY PLAN
SELECT SUM(amount) FROM payments WHERE paid_on >= '2025-03-01' AND paid_on < '2025-04-01';

-- Both give the same answer
SELECT
  (SELECT SUM(amount) FROM payments WHERE strftime('%Y-%m', paid_on) = '2025-03') AS with_function,
  (SELECT SUM(amount) FROM payments WHERE paid_on >= '2025-03-01' AND paid_on < '2025-04-01') AS with_range;

Output

+---------------+
| detail        |
+---------------+
| SCAN payments |
+---------------+
(1 row)

+-------------------------------------------------------------------+
| detail                                                            |
+-------------------------------------------------------------------+
| SEARCH payments USING INDEX idx_paid_on (paid_on>? AND paid_on<?) |
+-------------------------------------------------------------------+
(1 row)

+---------------+------------+
| with_function | with_range |
+---------------+------------+
| 10628266      | 10628266   |
+---------------+------------+
(1 row)
  • SCAN payments means the database reads all 50,000 rows. SEARCH ... USING INDEX means it jumps straight to the matching part of the index.
  • In the first query, strftime('%Y-%m', paid_on) has to be calculated for every row before it can be compared, so the index on paid_on is useless. The plan is a full scan.
  • The second query asks the same question as a range on the bare column: from March 1 up to, but not including, April 1. The index can find that range directly.
  • Both return the same total. A condition the index can use is called sargable (from “search argument able”).
Slow (not sargable)Fast rewrite
WHERE strftime('%Y', paid_on) = '2025'WHERE paid_on >= '2025-01-01' AND paid_on < '2026-01-01'
WHERE amount * 2 > 1000WHERE amount > 500
WHERE lower(email) = 'a@b.com'Store emails in lower case, or create an index on lower(email)
WHERE name LIKE '%rahman'LIKE 'rahman%' can often use an index (in SQLite only with a matching case setting); a leading % never can. Consider full-text search.

Composite and Covering Indexes

CREATE TABLE payments (id INTEGER PRIMARY KEY, customer_id INTEGER, paid_on TEXT, amount INTEGER, method TEXT);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 50000)
INSERT INTO payments (customer_id, paid_on, amount, method)
SELECT i % 2000, date('2025-01-01', '+' || (i % 365) || ' days'), (i * 37) % 5000,
       CASE i % 3 WHEN 0 THEN 'bkash' WHEN 1 THEN 'card' ELSE 'cash' END
FROM n;

-- A composite index: equality column first, range column second
CREATE INDEX idx_cust_date ON payments(customer_id, paid_on);
EXPLAIN QUERY PLAN
SELECT paid_on, amount FROM payments
WHERE customer_id = 42 AND paid_on >= '2025-06-01';

-- Leading column missing: the index cannot be used for the search
EXPLAIN QUERY PLAN
SELECT SUM(amount) FROM payments WHERE paid_on >= '2025-06-01';

-- A covering index holds every column the query needs, so the table is never read
CREATE INDEX idx_cust_amount ON payments(customer_id, amount);
EXPLAIN QUERY PLAN
SELECT customer_id, SUM(amount) FROM payments WHERE customer_id BETWEEN 10 AND 20 GROUP BY customer_id;

Output

+-------------------------------------------------------------------------+
| detail                                                                  |
+-------------------------------------------------------------------------+
| SEARCH payments USING INDEX idx_cust_date (customer_id=? AND paid_on>?) |
+-------------------------------------------------------------------------+
(1 row)

+---------------+
| detail        |
+---------------+
| SCAN payments |
+---------------+
(1 row)

+----------------------------------------------------------------------------------------+
| detail                                                                                 |
+----------------------------------------------------------------------------------------+
| SEARCH payments USING COVERING INDEX idx_cust_amount (customer_id>? AND customer_id<?) |
+----------------------------------------------------------------------------------------+
(1 row)
  • The index on (customer_id, paid_on) is sorted by customer first, then by date within each customer, like a phone book sorted by surname, then first name. The plan shows both columns used: customer_id=? AND paid_on>?.
  • Put columns tested with = first and the range column last. After a range, the index cannot narrow any further columns.
  • A query on paid_on alone cannot use this index, just as a phone book sorted by surname cannot find everyone called “Rahim”. The plan falls back to a full scan.
  • The last index contains every column the query needs (customer_id and amount). The plan says COVERING INDEX: the answer comes from the index alone, without touching the table.

More Quick Wins

  1. Select only the columns you need. SELECT * reads more data and prevents covering indexes.
  2. Index foreign key columns used in joins, such as enrollments.student_id.
  3. Avoid the N+1 pattern: running one query per row from a loop in your program. One join or IN (...) query is far faster than 1,000 small ones.
  4. Use keyset pagination instead of large OFFSET values, as shown in pagination.
  5. Refresh statistics with ANALYZE after big data changes, so the planner can choose well.
  6. Measure before and after. In the SQLite shell, .timer on prints the time of each query.

Common Mistakes

  1. Adding an index for every column. Each index slows down inserts and updates and uses disk space. Index what your slow queries actually filter, join and sort on.
  2. Testing on tiny tables. With 10 rows a full scan is fastest, so the plan will not show the problem.
  3. Comparing different types, such as a text column with a number. Some databases then convert every row and skip the index.
  4. Guessing instead of reading the plan. Always check EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) first.

Practice Exercises

Exercise 1. Rewrite WHERE substr(paid_on, 1, 7) = '2025-06' so it can use the index on paid_on.

Show answer
WHERE paid_on >= '2025-06-01' AND paid_on < '2025-07-01'

Exercise 2. Which single index best serves SELECT paid_on FROM payments WHERE method = 'bkash' AND amount > 4000?

Show answer

CREATE INDEX idx_method_amount_date ON payments(method, amount, paid_on); The equality column comes first, the range column second, and adding paid_on makes it a covering index.

Frequently Asked Questions

Why does the database sometimes ignore my index?

If a query matches a large share of the table, reading the whole table can be cheaper than jumping through the index for each row. The planner decides using statistics, so run ANALYZE and check that the condition is sargable.

Is a subquery slower than a join?

Not necessarily. Modern planners often turn one into the other. Write the clearest query first, then compare plans only if it is slow.

Summary

  • Read the plan: SCAN reads everything, SEARCH uses an index.
  • Keep indexed columns bare in WHERE; rewrite functions as ranges.
  • In composite indexes, put equality columns first and the range column last.
  • Covering indexes answer a query without reading the table.

Next: SQL Project: Sales Analysis Report.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *