SQL
5 min read
BEGINNER
Tie breaking
Quick AnswerWhen two rows have equal sort values, add another sort key to make their order predictable. A unique final key provides a total order.
Core idea
When two rows have equal sort values, add another sort key to make their order predictable. A unique final key provides a total order.
Minimal example
sql
SELECT customer_id, id FROM orders ORDER BY customer_id ASC, id ASC;Expected SQLite rows:
text
1 | 1011 | 1022 | 103How it works
In orders, customer 1 has two orders. ORDER BY customer_id, id first groups by customer and then sorts by unique order ID within each group. Direction applies separately to each key.
Practical example
sql
SELECT id FROM orders ORDER BY customer_id ASC, id DESC;Expected SQLite rows:
text
102101103Common mistake and practice
Do not rely on physical order for ties. Reverse only the order ID direction and predict 102, 101, 103.