HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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:
SELECT * FROM products ORDER BY Price;
You can click on above box to edit the code and run again.

Output

order_by

Syntax

SELECT   column1, column2, ... 
FROM  table_name
ORDER BY column1, column2, ... ASC| DESC ;

Demo Products table


This product table is used for examples:


product table

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:
SELECT * FROM products ORDER BY Price DESC ;

You can click on above box to edit the code and run again.

Output

order by price desc

Order Alphabetically


For string values the ORDER BY keyword will order alphabetically:

Example

Sort the products alphatbetically by Product_name:
SELECT * FROM products ORDER BY Product_name ;

You can click on above box to edit the code and run again.

Output

order by alphabetically

Alphabetically DESC


To sort the table reverse alphabetically, use the DESC keyword:

Example

Sort the products by Product_name in reverse order:

SELECT * FROM products ORDER BY Product_name DESC ;

You can click on above box to edit the code and run again.

Output

order by desc alphabetically

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

order by_ several column

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.

Output

order by_ asc and desc

Demo Employee table


This employee table is used for above examples:


demo employee table