SQL ORDER BY Clause
The ORDER BY
clause in SQL sorts the result set of a query. You can sort in ascending (ASC) or descending (DESC) order.
ORDER BY: Definition and Usage
ORDER BY
is essential for presenting data in a clear, organized way. It arranges the rows of your query's output according to the values in one or more columns. By default, ORDER BY
sorts in ascending order.
Default Sort Order (Ascending)
If you don't specify ASC
or DESC
, the sorting is ascending by default (for numbers: smallest to largest; for text: A to Z).
Syntax
SELECT * FROM Customers
ORDER BY CustomerName; -- Ascending (default)
Output
(Customers will be listed alphabetically by CustomerName from A to Z)
Sorting in Ascending Order (Explicit)
Explicitly specifying ascending order using the ASC
keyword.
Syntax
SELECT * FROM Customers
ORDER BY CustomerName ASC;
Output
(Customers will be listed alphabetically by CustomerName from A to Z)
Sorting in Descending Order
Specifying descending order using the DESC
keyword (for numbers: largest to smallest; for text: Z to A).
Syntax
SELECT * FROM Customers
ORDER BY CustomerName DESC;
Output
(Customers will be listed alphabetically by CustomerName from Z to A)