ORDER BY
Without ORDER BY, row order is not guaranteed.
Use explicit sorting whenever output order matters.
Core Concepts
flowchart TD
A[Unordered result rows] --> B[ORDER BY columns]
B --> C[ASC or DESC applied]
C --> D[Deterministic output order]
| Pattern | Example |
|---|---|
| Ascending | ORDER BY score ASC |
| Descending | ORDER BY score DESC |
| Multi-column | ORDER BY city ASC, score DESC |
Code Examples
-- Setup sample ranking table.
CREATE TABLE leaderboard (
player TEXT NOT NULL,
score INTEGER NOT NULL
);
INSERT INTO leaderboard (player, score)
VALUES ('Ava', 78), ('Ben', 92), ('Chen', 85);
| Expected output |
|---|
| Table created and three rows inserted. |
-- Highest scores first.
SELECT player, score
FROM leaderboard
ORDER BY score DESC;
| player | score |
|---|---|
| Ben | 92 |
| Chen | 85 |
| Ava | 78 |
SQLite-Specific Nuances
SQLite Nuance
SQLite supports ordering by selected columns, expressions, and column aliases.
Common Pitfalls / Best Practices
Pitfall
Assuming insertion order is equivalent to query order.
Best Practice
If users care about sequence, always declare it with ORDER BY.
Quick Challenge
Sort leaderboard by player alphabetically.
View Solution
SELECT player, score
FROM leaderboard
ORDER BY player ASC;
| player | score |
|---|---|
| Ava | 78 |
| Ben | 92 |
| Chen | 85 |