runtime
67 / 88

lesson 67 Performance & query plans · advanced

Indexes: observe a real access path

Create indexes and inspect their actual query plans.

the idea

An index offers an access structure at the cost of storage and write work. Use EXPLAIN QUERY PLAN to see SQLite choose SCAN, SEARCH, or a covering index. Plans describe physical access; they are not measured speed. This tiny dataset cannot establish a production performance improvement.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
CREATE INDEX idx_orders_customer ON orders(customer_id);
EXPLAIN QUERY PLAN
SELECT id,quantity
FROM orders
WHERE customer_id=1;

Watch for: SQL Server clustered/nonclustered and columnstore indexes have different storage details from SQLite indexes.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Plan a lookup before indexing. Without an index, filtering orders by customer_id may scan. EXPLAIN QUERY PLAN shows the current path.

    step-1.sql
    EXPLAIN QUERY PLAN
    SELECT id, quantity
    FROM orders
    WHERE customer_id = 1;
  2. Add an index and re-check the plan. CREATE INDEX can change the access path. Compare the new plan to the scan you saw before.

    step-2.sql
    CREATE INDEX idx_orders_customer ON orders(customer_id);
    EXPLAIN QUERY PLAN
    SELECT id,quantity
    FROM orders
    WHERE customer_id=1;

challenge 1

Create idx_orders_customer on orders(customer_id), then return id and quantity for customer_id=1. Run Query plan after the script to inspect the final SELECT.

Return idquantityany row ordertable changes are checked too

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.