SQL ORDER BY Clause
What is ORDER BY?
The ORDER BY clause sorts the result set of a query by one or more columns. By default rows are returned in an unspecified order; ORDER BY gives you control over the sequence.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC];ASC— ascending order (default).DESC— descending order.
When to Use
- Displaying results alphabetically
- Showing the most recent orders first
- Ranking students by grade
- Paginating data in a consistent sequence
Key Points
- Default is ASC — If you omit
ASCorDESC, PostgreSQL sorts in ascending order. - Multiple Columns — You can sort by several columns. The second column breaks ties in the first.
- NULLS FIRST / NULLS LAST — PostgreSQL lets you control where NULLs appear:
ORDER BY col ASC NULLS LAST. - Column Position — You can refer to columns by their position in the SELECT list:
ORDER BY 1. - Performance — Sorting large result sets can be expensive. An index on the sort column speeds things up.
ORDER BY is almost always paired with SELECT in user-facing queries to guarantee a predictable display order.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
SQL ORDER BY Clause Challenge
Write a query that solve this task: list all students in alphabetical order by name.
Expected result
All student rows sorted alphabetically from A to Z by first_name.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is ORDER BY?
Press Run to execute the query once the engine is ready.
More Examples
Sort orders by total descending
Show the highest-value orders first.
Press Run to execute the query once the engine is ready.
Multi-column sort
Sort employees by department, then by salary within each department.
Press Run to execute the query once the engine is ready.