ORDER BY
ORDER BY sorts the result by one or more columns, ascending or descending.
In this page:
Syntax
SELECT columns
FROM table_name
ORDER BY column1 DESC, column2 ASC;
ORDER BY
ASC is the default and DESC reverses the order. List several columns to break ties in order.
Sorting by an alias or column position is allowed. In PostgreSQL, NULLs sort last in ascending order by default, and NULLS FIRST or NULLS LAST can override that.
Note:
Without ORDER BY the row order is not guaranteed.
Example: ORDER BY
CREATE TABLE players (id INTEGER PRIMARY KEY, name TEXT, team TEXT, score INTEGER);
INSERT INTO players VALUES (1, 'Ada', 'red', 30), (2, 'Bob', 'blue', 50), (3, 'Cy', 'red', 50), (4, 'Di', 'blue', 10);
SELECT name, score FROM players ORDER BY score DESC, name ASC;
SELECT team, name FROM players ORDER BY team, score DESC;
-- Output:
-- name | score
-- Bob | 50
-- Cy | 50
-- Ada | 30
-- Di | 10
-- team | name
-- blue | Bob
-- blue | Di
-- red | Cy
-- red | Ada
Login to try C/C++/Java/PHP code in the editor
Related Topics
Common Mistakes
- Relying on an unsorted result order
- Forgetting DESC for top-N queries
- Sorting large results without an index
Chapter Summary
- ORDER BY sorts the result
- ASC default, DESC reverses
- Multiple columns break ties
- No ORDER BY means no guaranteed order
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: