SQL ORDER BY 子句

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, ... 是用于排序行的列

例如,

How to use ORDER BY in SQL
示例:SQL 中的 ORDER BY

ORDER BY ASC(升序)

我们可以使用 ASC 关键字显式地将选定的记录按升序排序。例如:

-- orders all rows from Customers in ascending order by age 
SELECT *
FROM Customers
ORDER BY age ASC;

在这里,SQL 命令从 Customers 表中选择所有行,然后按 age 升序排序。

How to use ORDER BY with ASC in SQL
示例:SQL 中的 ORDER BY ASC

注意: 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 降序排序。

How to use ORDER BY with DSC in SQL
示例:SQL 中的 ORDER BY DESC

多列排序

我们也可以使用 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 排序这些记录。

How to use ORDER BY with multiple columns in SQL
示例:SQL 多列排序

ORDER BY 与 WHERE

我们还可以将 ORDER BYSELECT 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_nameage 字段,如果他们的 country 不是 UK
  • 然后,所选记录按 last_name 降序排序。
How to use ORDER BY with WHERE in SQL
示例:SQL 中带 WHERE 的 ORDER BY

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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战