0%

Ask Precise Questions · practice

Break Ties with More Sort Keys

The seven-day cordless drill and folding table are tied. Asking only for loan_days DESC cannot decide which one belongs first, so two correct runs may show those rows in different positions.

Give SQLite more instructions by replacing the current ORDER BY line with this one:

ORDER BY loan_days DESC, name ASC, id ASC;

Press Run. The seven-day rows are still above the three-day row, and their names now settle the first tie:

TL-100 | Cordless drill | tools | 7
EV-101 | Folding table | events | 7
TL-220 | Step ladder | tools | 3

SQLite reads the sort keys from left to right. It first compares loan_days, with larger values first. Only when two periods are equal does it compare name, this time in ascending alphabetical order. If both the period and name match, id ASC makes the final decision.

Imagine two seven-day rows named Folding table, with IDs 12 and 90. The first key ties, and the second key ties too. SQLite reaches the third key and places ID 12 before ID 90. A later key never overturns a decision already made by an earlier one.

You did not add id to the result columns, and you do not need to. A column may help arrange the answer without being displayed. The visible result stays focused on the tag, name, category, and period.

Why include an ID after the name? A catalog may contain two different items with the same human-readable name. “Folding table” could describe several physical tables, while their explicit IDs still distinguish them. The final key gives every matching row one stable place, even when the earlier values tie.

The directions are deliberate too. loan_days DESC puts longer periods first; name ASC and id ASC put smaller text and ID values first within a tie. Changing the order of those keys changes the question. Sorting by ID before name would make the IDs settle a tie before the names get a chance.

Submit uses tied periods, repeated names, and scrambled insertion order. Check the complete ORDER BY rather than judging only the three visible rows. A query can look stable on this small catalog and still leave a tie unresolved.

Your result now has a complete order. Every qualifying row has a predictable position because each possible tie has a later key ready to settle it.

Task

Replace the one-key order in search.sql with loan_days DESC, name ASC, id ASC.

Run the query and submit it after checking that the sort keys appear in that order.