SQL Getting Sta...login
SQL Getting Started Tutorial Manual
author:php.cn  update time:2022-04-12 14:15:40

SQL ORDER BY



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 column or multiple columns.

The ORDER BY keyword sorts records in ascending order by default. If you need to sort 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 php sample database.

The following is the data selected from the "Websites" table:

+----+--------------+--- ------------------------+------+---------+
| id | name | url                                                                    --------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | Taobao | https://www.taobao.com/ | 13 | CN |
| 3 | php Chinese website | //m.sbmmt.com/ | 4689 | CN |
| 4 | Weibo | 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 "alexa" column sorting:

Example

SELECT * FROM Websites
ORDER BY alexa;
Execution output result:



ORDER BY DESC Example

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

Example

SELECT * FROM Websites
ORDER BY alexa DESC;

Execution output result:



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 result: