Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQL ORDER BY Keyword

SQL ORDER BY Keyword


The ORDER BY keyword is used to sort a result set.


SQL ORDER BY Keyword

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

The ORDER BY keyword sorts records in ascending order by default. To sort 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;


Demonstration Database

In this tutorial, we will use the RUNOOB 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  | Runoob Tutorial      | http://www.runoob.com/    | 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: