ORDER BY Clause
When working with data, the order of results matters. The ORDER BY clause allows us to sort query results in a meaningful way.
By default, SQL does not guarantee any order. ORDER BY gives us full control over how results are displayed.
What is ORDER BY?
The ORDER BY clause sorts the result set based on one or more columns.
Basic syntax:
SELECT column_name FROM table_name ORDER BY column_name;
Sorting can be done in:
- Ascending order (default)
- Descending order
Example Table
We will continue using the employees table:
+----+----------+------------+--------+ | id | name | department | salary | +----+----------+------------+--------+ | 1 | Alice | HR | 60000 | | 2 | Bob | IT | 75000 | | 3 | Charlie | Finance | 70000 | | 4 | Diana | IT | 80000 | +----+----------+------------+--------+
Sorting in Ascending Order (ASC)
Ascending order sorts values from:
- A → Z (text)
- Small → Large (numbers)
Example: Sort employees by salary (lowest first).
SELECT name, salary FROM employees ORDER BY salary ASC;
Since ASC is the default, it can be omitted.
Sorting in Descending Order (DESC)
Descending order sorts values from:
- Z → A (text)
- Large → Small (numbers)
Example: Sort employees by salary (highest first).
SELECT name, salary FROM employees ORDER BY salary DESC;
Sorting by Text Columns
ORDER BY also works with text columns.
Example: Sort employees alphabetically by name.
SELECT name, department FROM employees ORDER BY name;
Text sorting is usually case-insensitive in MySQL.
Sorting by Multiple Columns
You can sort by more than one column. SQL sorts using the first column, and if values are the same, it uses the next column.
Example: Sort by department first, then by salary.
SELECT name, department, salary FROM employees ORDER BY department ASC, salary DESC;
This query:
- Groups employees by department
- Sorts salaries within each department (highest first)
ORDER BY with WHERE
ORDER BY is often used together with WHERE.
Example: IT employees sorted by salary.
SELECT name, salary FROM employees WHERE department = 'IT' ORDER BY salary DESC;
Important rule:
WHEREfilters rowsORDER BYsorts the filtered result
Common Beginner Mistakes
- Using ORDER BY before WHERE
- Forgetting DESC when expecting highest values first
- Sorting numeric columns stored as text
Always check column data types to avoid unexpected results.
Why ORDER BY Matters
ORDER BY helps you:
- Rank data
- Find highest or lowest values
- Create readable reports
- Prepare data for analysis
Almost every reporting query uses ORDER BY.
What’s Next?
In the next lesson, we will limit the number of rows returned using the LIMIT clause.