SQL Basics
SQL ORDER BY
Sort query results in ascending or descending order using single or multiple columns.
The SQL ORDER BY Clause
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Sorting by Multiple Columns
You can sort by multiple columns. The result set is sorted by the first column, then by the second column for ties.
LIMIT and OFFSET
Use LIMIT to restrict the number of rows returned. Use OFFSET to skip rows — useful for pagination.
Example
sql
-- Ascending order (default)
SELECT name, price FROM products ORDER BY price;
-- Descending order
SELECT name, score FROM leaderboard ORDER BY score DESC;
-- Multiple columns
SELECT
last_name,
first_name,
salary
FROM employees
ORDER BY last_name ASC, first_name ASC;
-- Order by expression
SELECT name, price * quantity AS total
FROM order_items
ORDER BY total DESC;
-- LIMIT - top 10 results
SELECT name, views
FROM articles
ORDER BY views DESC
LIMIT 10;
-- Pagination with LIMIT + OFFSET
-- Page 1: OFFSET 0, Page 2: OFFSET 10, Page 3: OFFSET 20
SELECT * FROM products
ORDER BY created_at DESC
LIMIT 10 OFFSET 20; -- Page 3
-- NULLS LAST / FIRST (PostgreSQL)
SELECT name, last_login
FROM users
ORDER BY last_login DESC NULLS LAST;Want to run this code interactively?
Try in Compiler