关键字 ORDER BY 用于按升序或降序对结果集进行排序。
SQL 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. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | 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 |
以下 SQL 语句从“Customers”表中选择所有客户,并按“Country”(“国家/地区”)列排序:
Run SQLSELECT * FROM Customers
ORDER BY Country
以下 SQL 语句从“Customers”表中选择所有客户,并按“Country”(“Country”)列降序 (DESCending) 排序:
Run SQLSELECT * FROM Customers
ORDER BY Country DESC
以下 SQL 语句从 Customers 表中选择所有客户,并按列“Country”和“CustomerName”(“客户名称”)排序。 这意味着它将按国家/地区排序,但如果某些行具有相同的国家/地区,它们将按客户名称排序:
Run SQLSELECT * FROM Customers
ORDER BY Country, CustomerName
以下 SQL 语句从“Customers”表中选择所有客户,并按“Country”列升序排序,并按“CustomerName”列降序排序:
Run SQLSELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC