Build a covering index for receipt amounts
Your task
Create idx_receipts_date_amount on sold_on and amount, in that order. Then show the query plan for selecting amount on 2025-01-16, requiring the new index with INDEXED BY.
An index that contains all selected and filtered columns can answer a query without fetching table rows.
Sample data
receipts| id | sold_on | amount | channel | metadata |
|---|---|---|---|---|
| 1 | 2025-01-01 | 36 | ONLINE | {"currency":"EUR","tags":["gift","jazz"]} |
| 2 | 2025-01-16 | 22 | Store | {"currency":"EUR","tags":["indie"]} |
| 3 | 2025-01-31 | 54 | online | {"currency":"EUR","tags":["returning","bundle"]} |
| 4 | 2025-03-04 | 38 | STORE | {"currency":"EUR","tags":[]} |
| 5 | 2025-04-09 | 44 | Online | {"currency":"EUR","tags":["indie"]} |
Expected output
| id | parent | notused | detail |
|---|---|---|---|
| 2 | 0 | 55 | SEARCH receipts USING COVERING INDEX idx_receipts_date_amount (sold_on=?) |
Show a hint
Put sold_on first for the equality filter and amount second for the result column.
Indexes and query plans guide
Read SCAN and SEARCH
EXPLAIN QUERY PLAN describes access paths. SCAN indicates a scan of a table or index. SEARCH indicates that SQLite can use constraints to narrow the rows it visits. The exact plan depends on indexes, the query, and the database contents.
EXPLAIN QUERY PLAN
SELECT title FROM catalog WHERE stock = 3;
EXPLAIN QUERY PLAN
SELECT title FROM catalog WHERE genre = 'Jazz' AND price = 25;Use a composite index from the leading column
The catalog index orders entries by genre and then by price. Filtering by genre and a price range lets SQLite narrow the search and read prices in index order. Selecting only genre and price can make this a covering lookup, which avoids reading extra columns from the table.
EXPLAIN QUERY PLAN
SELECT genre, price
FROM catalog
WHERE genre = 'Jazz' AND price >= 20
ORDER BY price;Look for a separate sort
The plan may report a temporary B-tree when no available access path provides the requested order. A scan can still use an index, so look at the whole plan. Indexes trade read improvements for extra storage and work on writes.
EXPLAIN QUERY PLAN
SELECT title FROM catalog ORDER BY title;Worked solution
CREATE INDEX idx_receipts_date_amount ON receipts(sold_on,amount); EXPLAIN QUERY PLAN SELECT amount FROM receipts INDEXED BY idx_receipts_date_amount WHERE sold_on='2025-01-16';Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.
Results
Loading SQLite…
