The ORDER BY keyword in a SQL SELECT statement is used to sort a given result-set based on the contents of one or more columns of data. By default, results are in ascending order, but you can use either ASC or DESC to indicate that you’d like results sorted in ascending or descending order, respectively.
Below is a selection from the “Customers” table that we will use to run some SQL sorting statements using the ORDER BY keyword:
ID Site Contact Address City Zip Country
1 Krypted Charles Edge my house Minneapolis 55418 US
2 Apple Tim Cook spaceship Cupertino 95014 US
3 Microsoft Satya Nadella campus Redmond 98053 US
4 Facebook Mark Zuckerberg foodhall Menlo Park 94025 US
5 JAMF Dean Hager Grain Exchange Minneapolis 55418 US
The syntax we’ll use for these commands is:
SELECT column_name, column_name
FROM table
ORDER BY column ASC|DESC, column ASC|DESC;
Here is a basic SQL statement that selects all of the customers from the “Customers” table and sorts the results in ascending order (as it’s the default operation) based on the contents of the “Country” column:
SELECT * FROM Customers
ORDER BY Country;
Now we’ll flip that into descending order:
SELECT * FROM Customers
ORDER BY Country DESC;
Then ascending based on first the country, then the Site:
SELECT * FROM Customers
ORDER BY Country, Site;
Finally, you can do ascending for the country and descending for the site:
SELECT * FROM Customers
ORDER BY Country ASC, Site DESC;