ORDER BY Clause
The ORDER BY
clause sorts the result set of a SELECT
statement according to one or more columns or expressions.
Syntax
SELECT column_list
FROM table_name
[WHERE condition]
[ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...];
Key Points
- Default sort direction is ASC (ascending).
- Multiple columns can be specified to create hierarchical sorting.
- Expressions, functions, and column aliases can be used in the
ORDER BY
list. - When
ORDER BY
is omitted, the result set is unordered.
Examples
-- Sort employees by last name ascending
SELECT FirstName, LastName, HireDate
FROM Employees
ORDER BY LastName;
-- Sort products by price descending, then name ascending
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC, ProductName ASC;
Interactive Demo
Try sorting the sample data below:
ID | Name | Salary | Hire Date |
---|---|---|---|
3 | Alice Johnson | 72000 | 2019-04-12 |
1 | Bob Smith | 85000 | 2017-08-03 |
5 | Carol Lee | 66000 | 2020-01-15 |
2 | David Kim | 92000 | 2015-06-21 |
4 | Evelyn Chen | 78000 | 2018-11-30 |