SQL ORDER BY Clause
beginnerbasics
2 min read
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.
Practice challengeGuided learning mode
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?
Initializing database...Each run starts from fresh sample data.
More Examples
Sort orders by total descending
Show the highest-value orders first.
Initializing database...Each run starts from fresh sample data.
Multi-column sort
Sort employees by department, then by salary within each department.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the default sort order in SQL?
The default sort order is ascending (ASC). If you omit ASC or DESC, the database sorts from smallest to largest or A to Z.
Can I ORDER BY a column not in the SELECT list?
Yes. You can sort by any column in the table, even if it is not included in the SELECT list.