SQL – ORDER BY
Sort your query results ascending or descending using the ORDER BY clause.
Table of Contents
Data stored in a database has no guaranteed order — rows can appear in any sequence depending on when they were inserted or how the storage engine organizes them. The ORDER BY clause lets you declare exactly how you want results sorted. Need the top scorers first? Sort by score descending. Building an alphabetical directory? Sort by name ascending.
You can sort by multiple columns — if two rows have the same value in the first sort column, the second column acts as a tiebreaker. This is called a multi-level sort and is surprisingly powerful for generating ranked reports.
Syntax
-- Single column sort
SELECT * FROM students ORDER BY score DESC;
-- Multi-column sort (age first, then score)
SELECT * FROM students ORDER BY age ASC, score DESC;
Try It Yourself — Interactive SQL Editor
Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.
Key Points
- Default sort direction is ASC (ascending) if not specified
- DESC reverses the order — highest values first
- NULLs are typically sorted last in ASC, first in DESC
- ORDER BY can reference column position: ORDER BY 3 DESC
Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.
In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.