SQL and databases

Stage 2 · Lesson 4 of 8

Sorting with ORDER BY

Querying one table

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

  • CoursePaid
    Grokking SQL for Tech Interviews

    Design Gurus · Intermediate · Subscription

    The basics, order of execution and functions chapters, each followed by graded problems

  • CourseFree
    SQLBolt

    SQLBolt · Beginner

    Free: Lessons 1 to 4, 8, 9 and 12 cover SELECT, filtering, sorting, NULLs, expressions and query order

Practise

Keep handy

  • The T-SQL SELECT, TOP and ORDER BY pages and the date and time functions list

  • Its SQL pages give quick examples and note where MySQL and SQL Server syntax differ

Also worth your time

Mark this stage as not done?