ORDER BY and Sorting Results
What you'll learn: How to control the order of rows returned by your SQL queries using the ORDER BY clause.
What Is Sorting in SQL?
By default, SQL databases return query results in no guaranteed order—they might appear in insertion order, or in whatever sequence is most efficient for the database engine. The ORDER BY clause gives you explicit control over how rows are sorted in your result set.
Think of it like organizing books on a shelf: you can arrange them alphabetically by title, by author, by publication date, or even by multiple criteria (author first, then title within each author).
Basic Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1;
This sorts results by column1 in ascending order (A-Z, 0-9, oldest-to-newest) by default.
Ascending vs Descending
- ASC (ascending): smallest to largest, A to Z
- DESC (descending): largest to smallest, Z to A
SELECT name, salary
FROM employees
ORDER BY salary DESC;
This shows highest-paid employees first.
Sorting by Multiple Columns
You can sort by multiple columns—the database sorts by the first column, then breaks ties using the second column, and so on:
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
This groups employees by department (alphabetically), then within each department, shows highest salaries first.
Practical Example
SELECT product_name, price
FROM products
WHERE price > 10
ORDER BY price ASC, product_name ASC;
This filters products over $10, sorts by price (cheapest first), and alphabetically by name when prices match.
Key Takeaway: The ORDER BY clause sorts query results by one or more columns in ascending (ASC, default) or descending (DESC) order, giving you complete control over how data is presented.