The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, …
FROM table_name
ORDER BY column1, column2, … ASC|DESC;
Demo Database
Below is a selection from the “Customers” table in the Northwind sample database:
The following SQL statement selects all customers from the “Customers” table, sorted by the “Country” column:
SELECT * FROM Customers
ORDER BY CustomerID;
This Result
ORDER BY Several Columns Example
The following SQL statement selects all customers from the “Customers” table, sorted by the “CustomerID” and the “PostalCode” column. This means that it orders by CustomerID, but if some rows have the same CustomerID, it orders them by PostalCode:
SELECT * FROM Customers
ORDER BY CustomerID, PostalCode;
ORDER BY DESC Example
The following SQL statement selects all customers from the “Customers” table, sorted DESCENDING by the “Country” column:
SELECT * FROM Customers
ORDER BY CustomerID DESC;
This is result
ORDER BY ASC Example
The following SQL statement selects all customers from the “Customers” table, sorted abbreviation by the “Country” column:
SELECT * FROM Customers
ORDER BY CustomerID ASC;
This is result
- Best AI tools for Software Engineers - November 4, 2024
- Installing Jupyter: Get up and running on your computer - November 2, 2024
- An Introduction of SymOps by SymOps.com - October 30, 2024