SQL — Order By
Basic ORDER BY
-- Ascending (default)
SELECT * FROM users ORDER BY name;
-- Descending
SELECT * FROM users ORDER BY name DESC;
Multiple columns
SELECT * FROM users
ORDER BY age DESC, name ASC;
ORDER BY with expressions
SELECT name, price, price * 0.9 AS discounted
FROM products
ORDER BY price * 0.9;
ORDER BY column number
SELECT name, age, email
FROM users
ORDER BY 2 DESC; -- Sort by age
ORDER BY with NULL
-- NULLs first (PostgreSQL)
SELECT * FROM users ORDER BY phone NULLS FIRST;
-- NULLs last (PostgreSQL)
SELECT * FROM users ORDER BY phone NULLS LAST;
-- MySQL: NULLs are treated as lowest value
SELECT * FROM users ORDER BY phone;
ORDER BY with LIMIT
-- Top 5 oldest users
SELECT * FROM users
ORDER BY age DESC
LIMIT 5;
-- Top 10% (PostgreSQL)
SELECT * FROM users
ORDER BY age DESC
FETCH FIRST 10 PERCENT ROWS ONLY;
Mini Practice
Write SQL code that:
- Sorts by a single column
- Sorts by multiple columns
- Orders with NULL handling
- Combines ORDER BY with LIMIT
Up Next
In the next lesson, you'll learn about Group By — aggregating data.
Related Topics
Frequently Asked Questions about Order By
What is Order By in SQL?
Order By is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Order By?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Order By.
Why is Order By important in SQL?
Order By is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.