How can I sort SQLite results predictably when values tie?
Quick answer
Add another expression to ORDER BY to specify how rows tied on the first expression should be ordered. For example, ORDER BY score DESC, player_id ASC sorts scores from highest to lowest, then IDs from lowest to highest within each tied score. The secondary expression should distinguish the rows whose order matters; rows tied on every listed expression still have no specified relative order. [S1]
The question, the details, the next step.
A practical checklist
State the primary ordering rule, such as highest score first.
Choose a secondary expression that defines the order of rows tied on the primary value.
Set each expression’s direction to match the intended order.
Check whether the expressions distinguish every tied row whose relative order matters.
Use an example to review the requested sequence.
A few more useful answers
If I omit the secondary expression, will SQLite sort ties by row ID automatically?
Do not rely on an unstated tie-breaker. The relative order of rows tied on every listed ORDER BY expression is undefined, so include the ordering rule you need. [S1]
What if my secondary column also has duplicate values?
Add another expression that distinguishes those rows if their relative order matters. Rows tied on every listed expression have no specified relative order. [S1]
Can I use different directions for the two sort rules?
Yes. ORDER BY score DESC, player_id ASC means scores descend, while IDs ascend within equal scores.
Sources
References used for this guide.
- [S1] SQLite SELECT — ORDER BY sorting and ties sqlite.org · Checked
