SQL ORDER BY
Keyword
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 one or multiple columns.
The ORDER BY keyword sorts the 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 column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
- column1, column2, ...: The field names to sort by, which can be multiple fields.
- ASC: Indicates sorting in ascending order.
- DESC: Indicates sorting in descending order.
Demo Database
In this tutorial, we will use the tutorialpro sample database.
Below is the data selected from the "Websites" table:
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | tutorialpro.org | http://www.tutorialpro.org/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 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 by the "alexa" column in descending order:
Example
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:
Example
SELECT * FROM Websites
ORDER BY country, alexa;
Execution output: