SQL Tutorial: ORDER BY & LIMIT
Sort query results with ORDER BY and retrieve top N rows with LIMIT and OFFSET.
ORDER BY
Sort results by one or more columns:
```sql
-- Ascending (default)
SELECT name, price FROM products ORDER BY price;
-- Descending
SELECT name, salary FROM employees ORDER BY salary DESC;
-- Multiple columns — sort by dept, then by name within each dept
SELECT name, dept, salary FROM employees
ORDER BY dept ASC, salary DESC;
```
---
LIMIT and OFFSET
Retrieve only N rows:
```sql
-- Top 5 most expensive products
SELECT name, price FROM products ORDER BY price DESC LIMIT 5;
-- Skip first 10, get next 5 (pagination)
SELECT name FROM users ORDER BY created_at DESC LIMIT 5 OFFSET 10;
```
---
NULL Ordering
NULLs appear last by default in ascending order, first in descending:
```sql
-- Put NULLs last regardless of sort direction
SELECT name, bio FROM users ORDER BY bio NULLS LAST;
```
---
What's Next?
Next: **Aggregate Functions** — `COUNT`, `SUM`, `AVG`, `MIN`, `MAX`.
What you'll learn in this SQL order by & limit tutorial
This interactive SQL tutorial has 3 hands-on exercises. Estimated time: 8 minutes.
- ORDER BY — sort employees by salary — `ORDER BY` controls the order of results. Without it, the database returns rows in an undefined order — never rely on it…
- Multi-column ORDER BY — sort by department, then salary — You can sort by multiple columns. The database sorts by the first column, then breaks ties using the second column.
- LIMIT and OFFSET — top N and pagination — `LIMIT N` returns at most N rows. `OFFSET M` skips the first M rows. Together they power pagination in web apps and 'top…
SQL ORDER BY & LIMIT concepts covered
- ORDER BY
- LIMIT and OFFSET
- NULL Ordering
- What's Next?