SQL Order By
The ORDER BY clause sorts the rows in a result set by one or more columns, in ascending or descending order.
Sorting your results
By default, a database returns rows in no guaranteed order, so the sequence you see can change from one run to the next. When the order matters, add an ORDER BY clause. It arranges the result set based on the values in a column you choose, making the output predictable and easier to read.
Sorting by one column
SELECT ProductName, Price
FROM Products
ORDER BY Price;The query above lists products from the cheapest to the most expensive. When you do not specify a direction, ORDER BY sorts in ascending order, which means smallest to largest for numbers and A to Z for text.
Ascending and descending order
You can control the direction of the sort with the ASC and DESC keywords. ASC produces ascending order and is the default, so it is often left out. DESC reverses the order, giving you largest to smallest or Z to A.
Sorting from highest to lowest
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC;Sorting by several columns
You can list more than one column after ORDER BY, separated by commas. The database sorts by the first column, and only when two rows share the same value in that column does it use the next column to break the tie. Each column can have its own direction.
Sorting by two columns with different directions
SELECT CustomerName, Country, City
FROM Customers
ORDER BY Country ASC, City DESC;- ORDER BY is written after the WHERE clause when both are present.
- You can sort by a column even if it is not part of the SELECT list.
- Some databases let you sort by a column's position number, such as ORDER BY 2, though naming the column is clearer.
- Sorting by text respects your database's collation, which decides how letters and accents compare.
Exercise: SQL Order By
If no sort direction is specified, ORDER BY sorts results: