| ISSUE 41/456 · COMPUTER SCIENCE |
~4 MIN |
FOUNDATION / DATABASES · READING DATE 2026-11-11 · NOVEMBER 2026 — THE SYSTEMS AROUND YOU
Why the order of database columns changes a search
START HERE
A contact list can be arranged by surname first or given name first. A database is an organised store of records, such as those contacts. An index is a separate lookup structure that helps software find selected records. An ordered index can put matching names together or scatter them, depending on which part of a name it sorts first.
|
/ WHY NOW
An address-book app might quickly find everyone called Smith but work harder to find everyone called Ana. Both names can be present in the index; what matters is which comes first in its ordering.
|
/ THE IDEA
A composite index combines multiple columns: named fields such as surname and given_name. In the common ordered design called a B-tree, entries are compared by their first column; the second breaks ties. This is lexicographic order: dictionary-style sorting extended to a pair. Fixing the first column to one value selects an uninterrupted run. Adding a range on the next column can select part of that run. These leading fields form a leftmost prefix; knowing only a later field need not identify one continuous section.
THE FORMAL IDEA
index key = (surname, given_name)
| key = the ordered pair used to place an entry. Here surname comes first, then given name. | | ≥ Bo means Bo or a later given name in the chosen alphabetical order, not a numerical comparison. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Surname-first: Brown/Ana, Brown/Bo, Jones/Ana, Jones/Cy, Smith/Ana, Smith/Bo, Smith/Cy. surname = Smith → entries 5–7 form one continuous run. surname = Smith and given_name ≥ Bo → entries 6–7: Smith/Bo and Smith/Cy. given_name = Ana → entries 1, 3 and 5 are separated. Change to (given_name, surname): Ana/Brown, Ana/Jones, Ana/Smith, Bo/Brown, Bo/Smith, Cy/Jones, Cy/Smith. The same Ana query now matches entries 1–3, a continuous run.
|
The contacts and matching answers did not change. Only the index order changed, making the first-name search fit one uninterrupted section instead of several separated entries.
/ SO WHAT?
If both names are fixed, either ordering can isolate that pair. Order matters especially when a query supplies only one name, or fixes one field and requests a range in another.
ONE CAVEAT |
| A nonleading column is not automatically unusable. PostgreSQL can check it during an index scan and sometimes use skip scan: repeated searches over leading values. The chosen plan depends on data and costs; the toy does not predict timing or every index type. |
KEEP THIS
Changing an ordered index’s leading columns changes which partial searches naturally map to one continuous range.
|
NEXT: Why one particular speed makes something rattle
|