Databases & SQL Master Course — 124. Composite Indexes
Lesson 124 Composite Indexes
Prerequisites and objectives
Complete the single-column index lesson. You will read a composite key as a lexicographic ordering, connect leading equality conditions and a later range to an access path, explain a sort that remains necessary, and compare candidate key orders without changing query results.
Read a composite key from left to right
An index on team, status, opened_day, and identity groups entries by team first. Within a team it groups by status, then by day, then identity. It is not four independent single-column indexes. The ordering of earlier keys determines which later values form a contiguous searchable interval.
A query fixing team and status can then search a day range within that group. A query fixing only team cannot assume all its dates are globally ordered, because status divides that team’s entries first. This distinction often explains why a composite index helps filtering but still leaves a sort in the plan.
Create a ticket workload
The fixture contains 2,000 deterministic tickets across ten teams, two statuses, and a set of October dates. Dates are canonical fixed-width text for this SQLite exercise. The report wants the first five open tickets for one team within a half-open date window, ordered by day and identity.
CREATE TABLE lab_tickets124(id INTEGER PRIMARY KEY, team TEXT NOT NULL, status TEXT NOT NULL, opened_day TEXT NOT NULL, detail TEXT NOT NULL);
WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<2000)
INSERT INTO lab_tickets124 SELECT x,'T'||(x%10),CASE WHEN x%3=0 THEN 'open' ELSE 'closed' END,printf('2026-10-%02d',(x%28)+1),'ticket-'||x FROM n;
Match equality, range, and output order
The candidate index starts with the two equality-filtered columns, followed by the date range and deterministic identity tie-breaker. This gives the planner a useful contiguous key interval and the requested order within that interval. All required output values are also present in the index, though coverage is examined more fully in the next lesson.
BEGIN;
CREATE INDEX lab_team_status_day124 ON lab_tickets124(team,status,opened_day,id);
SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' AND status='open' AND opened_day>='2026-10-05' AND opened_day<'2026-10-11' ORDER BY opened_day,id LIMIT 5;
EXPLAIN QUERY PLAN SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' AND status='open' AND opened_day>='2026-10-05' AND opened_day<'2026-10-11' ORDER BY opened_day,id LIMIT 5;
ROLLBACK;
| Ticket ID | Opened day |
|---|---|
| 33 | 2026-10-06 |
| 453 | 2026-10-06 |
| 873 | 2026-10-06 |
| 1293 | 2026-10-06 |
| 1713 | 2026-10-06 |
The local plan searches using the composite index. The equality prefix narrows team and status before the day range is traversed. Do not turn this into an absolute rule that every column after a range can never help: later columns may still support filtering, covering, or special optimizer strategies even when they do not further narrow a simple contiguous search interval.
Likewise, an unconstrained leading column does not make every possible use of an index impossible. Some engines and data distributions support skip-scan strategies, and an index can be scanned for coverage or order. The reliable claim is that omitting the leading key changes the straightforward prefix-search opportunity; inspect the actual plan.
Worked practice
Exercise 1
Remove the status predicate and ask for one team’s earliest tickets by day.
Worked solution
BEGIN;
CREATE INDEX lab_team_status_day124 ON lab_tickets124(team,status,opened_day,id);
SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' ORDER BY opened_day,id LIMIT 5;
EXPLAIN QUERY PLAN SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' ORDER BY opened_day,id LIMIT 5;
ROLLBACK;
The local plan requires ordering work because status separates the team’s date sequences. An index useful for the original open-ticket query is not automatically ideal for every team query. The remaining sort is a consequence of the requested global day order within the team.
Exercise 2
Count open tickets across all teams with the same index present.
Worked solution
BEGIN;
CREATE INDEX lab_team_status_day124 ON lab_tickets124(team,status,opened_day,id);
SELECT COUNT(*) FROM lab_tickets124 WHERE status='open';
EXPLAIN QUERY PLAN SELECT COUNT(*) FROM lab_tickets124 WHERE status='open';
ROLLBACK;
The predicate does not constrain the leading team key. In this recorded fixture the index may still be useful as a covering structure to scan, but that is different from a direct team-and-status search. The count remains a semantic assertion independent of the chosen access strategy.
Exercise 3
Try the alternative team, day, status key order for the original report.
Worked solution
BEGIN;
CREATE INDEX lab_team_day_status124 ON lab_tickets124(team,opened_day,status,id);
SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' AND status='open' AND opened_day>='2026-10-05' AND opened_day<'2026-10-11' ORDER BY opened_day,id LIMIT 5;
EXPLAIN QUERY PLAN SELECT id,opened_day FROM lab_tickets124 WHERE team='T3' AND status='open' AND opened_day>='2026-10-05' AND opened_day<'2026-10-11' ORDER BY opened_day,id LIMIT 5;
ROLLBACK;
The result is unchanged. The day range now appears before status in the index ordering, so status is not part of the same simple equality prefix. The alternative may scan more entries within the team’s date range. Its usefulness depends on other queries and data distribution, not just this one plan label.
Exercise 4
Remove the LIMIT to verify the complete qualifying set has stable boundaries.
Worked solution
BEGIN;
CREATE INDEX lab_team_status_day124 ON lab_tickets124(team,status,opened_day,id);
SELECT COUNT(*),MIN(opened_day),MAX(opened_day) FROM lab_tickets124 WHERE team='T3' AND status='open' AND opened_day>='2026-10-05' AND opened_day<'2026-10-11';
ROLLBACK;
The aggregate checks the full qualifying population rather than only the first page. A LIMIT can hide mistakes in later rows, so keep an unbounded correctness assertion when evaluating candidate access paths. The exclusive end date remains part of the contract.
Choose column order from the workload
List the important query shapes before deciding the key order. Consider which columns are equality filters, which are ranges, which sorts matter, and which columns are returned. Also consider whether a shorter prefix index is already present and whether a wider candidate duplicates its role at additional write cost.
Do not apply “most selective column first” as a universal recipe. Equality-prefix combinations, sort requirements, joins, and other queries can make a different order more useful. Measure representative parameter values, including common and rare groups, and retain the smallest justified set of indexes.
Pitfalls and summary
A composite index provides one ordered key sequence. Understand that sequence before interpreting plan output. Test omitted leading predicates, range boundaries, tied dates, and full results beyond LIMIT. An observed plan is evidence for one environment, not a promise that every optimizer version makes the same choice.
Knowledge check
Question 1
How is the candidate composite index ordered?
- By team, then status within team, then day and identity
- By each column independently in four unrelated structures
- By whichever WHERE predicate appears first in the SQL text
- By day globally before considering team
Answer and explanation
A. A composite index has a lexicographic key sequence.
Question 2
Why can the original query use a useful equality prefix?
- LIMIT automatically turns every key into an equality predicate
- ORDER BY removes the need for a leading-key condition
- It fixes team and status before applying the day range
- Every composite index treats all range conditions as equalities
Answer and explanation
C. The leading fixed keys identify a group whose following day values form a searchable range.
Question 3
Why can sorting remain when status is not constrained?
- SQLite cannot sort rows read through an index
- A LIMIT always forces a sort regardless of index order
- The final id key precedes opened_day in this index
- Status separates the team’s date sequences in the index
Answer and explanation
D. The requested team-wide date order differs from status-then-date traversal.
Question 4
What is the careful claim when the leading team key is unconstrained?
- The index becomes impossible to use for any purpose
- The simple prefix-search opportunity changes; inspect other possible index uses
- The index automatically reorganizes itself with status first
- Every engine must perform the same skip scan
Answer and explanation
B. Coverage, scanning, and optimizer-specific strategies can still matter.
Question 5
Why verify the complete set beyond LIMIT?
- The preview’s first rows prove that omitted rows cannot differ
- Removing LIMIT guarantees the fastest access path
- A correct-looking first page can hide errors in later qualifying rows
- A limited query never needs deterministic ordering
Answer and explanation
C. A bounded preview is weaker correctness evidence than checking the complete qualifying contract.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- Composite query planning: Multi-column ordering and search/sort relationships.
- Optimizer overview: Prefix constraints, ranges, and skip-scan considerations.
- Query plans: Search and sorting diagnostics.