The SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
Example
Sort the products by price:You can click on above box to edit the code and run again.
SELECT * FROM products ORDER BY Price;
Output
Syntax
SELECT column1, column2, ... FROM table_name
ORDER BY column1, column2, ... ASC| DESC ;
Demo Products table
This product table is used for examples:
DESC
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Example
Sort the products from highest to lowest price:You can click on above box to edit the code and run again.
SELECT * FROM products ORDER BY Price DESC ;
Output
Order Alphabetically
For string values the ORDER BY keyword will order alphabetically:
Example
Sort the products alphatbetically by Product_name:You can click on above box to edit the code and run again.
SELECT * FROM products ORDER BY Product_name ;
Output
Alphabetically DESC
To sort the table reverse alphabetically, use the DESC keyword:
Example
Sort the products by Product_name in reverse order:You can click on above box to edit the code and run again.
SELECT * FROM products ORDER BY Product_name DESC ;
Output
ORDER BY Several Columns
The below SQL statement selects all employee from the "employee" table, sorted by the "City" and the "Employee_name" column. This means that it orders by City, but if some rows have the same City, it orders them by Employee_name :
Example
SELECT * FROM employee ORDER BY City , Employee_name;You can click on above box to edit the code and run again.
Output
Using Both ASC and DESC
The below SQL statement selects all employee from the "employee" table, sorted ascending by the "City" and descending by the "Employee_name" column:
Example
SELECT * FROM employee ORDER BY City ASC , Employee_name DESC ;You can click on above box to edit the code and run again.