Stage 2 · Lesson 4 of 8
Sorting with ORDER BY
sorts the result by one or more columns or calculations. It sorts ascending (smallest first) by default, or descending if you add DESC. Without ORDER BY, the database may return rows in any order it finds convenient.
That order can change as the data grows or the database picks a different plan. Sort by several columns to break ties. When you need a stable order for paging through results, add a unique column such as id last.
Where go depends on the database. In ascending order puts them last, while and put them first. PostgreSQL also lets you choose with NULLS FIRST or NULLS LAST.
Common traptrusting that rows come back in the order you inserted them, just because they did on a small table.
A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock
Resources for this stage
Start with· follow one of these
- CoursePaidGrokking SQL for Tech Interviews
Design Gurus · Intermediate · Subscription
The basics, order of execution and functions chapters, each followed by graded problems
- CourseFreeSQLBolt
SQLBolt · Beginner
Free: Lessons 1 to 4, 8, 9 and 12 cover SELECT, filtering, sorting, NULLs, expressions and query order
Practise
Keep handy
Also worth your time
Walks through the logical order a query is evaluated in, which explains most early errors