SQL 中的 ORDER BY
子句用于将结果集按升序或降序排序。
示例
-- orders all rows from Customers in ascending order by country
SELECT *
FROM Customers
ORDER BY country;
在这里,SQL 命令从 Customers 表中选择所有行,然后按 country 升序排序。
SQL ORDER BY 语法
SQL ORDER BY
语句的语法是
SELECT column1, column2, ...
FROM table
ORDER BY columnA, columnB, ...;
这里,
column1, column2, ...
是要包含在结果集中的列table
是从中选择行的表的名称columnA, columnB, ...
是用于排序行的列
例如,

ORDER BY ASC(升序)
我们可以使用 ASC
关键字显式地将选定的记录按升序排序。例如:
-- orders all rows from Customers in ascending order by age
SELECT *
FROM Customers
ORDER BY age ASC;
在这里,SQL 命令从 Customers
表中选择所有行,然后按 age 升序排序。

注意: ORDER BY
子句默认按升序排序结果集,即使没有 ASC
子句。
ORDER BY DESC(降序)
我们使用 DESC
关键字将选定的记录按降序排序。例如:
-- order all rows from Customers in descending order by age
SELECT *
FROM Customers
ORDER BY age DESC;
在这里,SQL 命令选择所有客户,然后按 age 降序排序。

多列排序
我们也可以使用 ORDER BY
与多列。例如:
-- sort all rows from Customers, first by first_name and then by age
SELECT *
FROM Customers
ORDER BY first_name, age;
在这里,SQL 命令选择所有记录,然后按 first_name 排序。如果 first_name 重复多次,则按 age 排序这些记录。

ORDER BY 与 WHERE
我们还可以将 ORDER BY
与 SELECT WHERE
子句一起使用。例如:
-- select last_name and age of customers who don't live in the UK
-- and sort them by last_name in descending order
SELECT last_name, age
FROM Customers
WHERE NOT country = 'UK'
ORDER BY last_name DESC;
这里,
- SQL 命令首先从 Customers 表中选择 last_name 和 age 字段,如果他们的 country 不是 UK。
- 然后,所选记录按 last_name 降序排序。

注意: 当将 WHERE
子句与 ORDER BY
一起使用时,WHERE
子句总是先出现。
另请阅读