WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

SQL ORDER BY Keyword


The

ORDER BY keyword is used to sort the result set.


SQL ORDER BY keyword

ORDER BY keyword is used to sort the result set by one or more columns.

The ORDER BY keyword sorts records in ascending order by default. If you need to sort the records in descending order, you can use the DESC keyword.

SQL ORDER BY syntax

SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;


Demo database

In this tutorial, we will use the welookups sample database.

Here is the data from the "Websites" table:

+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.com/  | 1     | USA     |
| 2  | Indiatimes          | https://www.Indiatimes.com/ | 13    | IN      |
| 3  | zomato      | http://www.zomato.com/  | 88        | IN      |
| 4  | indiamart          | http://indiamart.com/       | 20    | IN      |
| 5  | Facebook     | https://www.facebook.com/| 3     | USA     |
+----+--------------+---------------------------+-------+---------+

ORDER BY example

The following SQL statement selects all websites from the "Websites" table and sorts them by the "alexa" column:

Example

SELECT * FROM Websites ORDER BY alexa;

Execution output:



ORDER BY DESC example

The following SQL statement selects all websites from the "Websites" table and sorts them in descending order by the "alexa" column:

Examples

SELECT * FROM Websites ORDER BY alexa DESC;

Execution output:



ORDER BY multiple columns

The following SQL statement selects all websites from the "Websites" table and sorts them by the "country" and "alexa" columns:

Examples

SELECT * FROM Websites ORDER BY country,alexa;

Execution output: