The ORDER BY keyword is used to sort the result set.
SQL ORDER BY keyword
The ORDER BY keyword is used to sort the result set by a column or columns.
The ORDER BY keyword sorts the records 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;
FROM table_name
ORDER BY column_name , column_name ASC|DESC;
Demo database
In this tutorial, we will use the RUNOOB sample database.
The following is the data selected from the "Websites" table:
+ ---- + -------------- + --------------------------- + - ------ + --------- + | Id | name | url | alexa | country | + ---- + -------------- + --------------------------- + - ------ + --------- + | 1 | Google | https://www.google.cm/ | 1 | USA | | 2 | Taobao | https://www.taobao.com/ | 13 | CN | | 3 | rookie tutorial | http://www.runoob.com/ | 4689 | CN | | 4 | microblogging | http://weibo.com/ | 20 | CN | 5 | Facebook | https://www.facebook.com/ | 3 | USA | + ---- + -------------- + --------------------------- + - ------ + --------- +
ORDER BY instance
The following SQL statement selects all sites from the "Websites" table and sorts them according to the "alexa" column:
Examples
SELECT * FROM Websites
ORDER BY Alexa
Execute the output:
ORDER BY DESC instance
The following SQL statement selects all sites from the "Websites" table and sorts them in descending order of "alexa"
Examples
SELECT * FROM Websites
ORDER BY Alexa DESC ;
Execute the output:
ORDER BY multiple columns
The following SQL statement selects all sites from the "Websites" table and sorts them according to the "country" and "alexa" columns:
Examples
SELECT * FROM Websites
ORDER BY Country , alexa
Execute the output: