Skip to main content

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]
PatternExample
AscendingORDER BY score ASC
DescendingORDER BY score DESC
Multi-columnORDER 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;
playerscore
Ben92
Chen85
Ava78

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;
playerscore
Ava78
Ben92
Chen85