ORDER BY Clause
The ORDER BY
clause sorts the result set of a SELECT
statement by one or more columns. By default, sorting is ascending (ASC
). Use DESC
for descending order.
Syntax
SELECT column1, column2, ...
FROM table_name
[WHERE condition]
[GROUP BY column1, column2, ...]
[HAVING condition]
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Basic Example
SELECT FirstName, LastName, HireDate
FROM Employees
ORDER BY HireDate DESC;
This returns employees ordered by their hire date, newest first.
Multiple Columns
SELECT ProductName, Category, Price
FROM Products
ORDER BY Category ASC, Price DESC;
First groups rows by Category
(alphabetically). Within each category, rows are sorted by Price
from highest to lowest.
Using Column Position
SELECT FirstName, LastName, Salary
FROM Staff
ORDER BY 3 DESC;
Sorting by the third column (Salary
) without naming it.
Collation and Case Sensitivity
Control sorting behavior with COLLATE
or by setting database collation. Example:
SELECT Name FROM Customers
ORDER BY Name COLLATE Latin1_General_CS_AS;