轻松上手,快乐学习!

SQL ORDER BY 关键字


SQL ORDER BY关键字

ORDER BY关键字用于按升序或降序对结果集进行排序。 ORDER BY关键字默认按升序对记录进行排序。要按降序对记录进行排序,请使用DESC关键字。

按语法排序

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

演示数据库

以下是Northwind示例数据库中“Customers”表的选择:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constituciуn 2222 Mйxico D.F. 05021 Mexico
3 Antonio Moreno Taquerнa Antonio Moreno Mataderos 2312 Mйxico D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbkцp Christina Berglund Berguvsvдgen 8 Luleе S-958 22 Sweden

ORDER BY示例

以下SQL语句从“Customers”表中选择所有客户,按“Country”列排序:

实例

SELECT * FROM Customers
ORDER BY Country;
运行实例»

ORDER BY DESC 实例

以下SQL语句从“Customers”表中选择所有客户,按“Country”列排序DESCENDING:

实例

SELECT * FROM Customers
ORDER BY Country DESC;
运行实例»

按几列排序实例

以下SQL语句从“Customers”表中选择所有客户,按“Country”和“CustomerName”列排序。这意味着它按Country排序,但如果某些行具有相同的国家/地区,则按CustomerName对它们进行排序:

实例

SELECT * FROM Customers
ORDER BY Country, CustomerName;
运行实例»

按几列排序示例2

以下SQL语句从“Customers”表中选择所有客户,按“Country”升序排序,然后按“CustomerName”列降序:

实例

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
运行实例»