> For the complete documentation index, see [llms.txt](https://404dream.gitbook.io/mysql/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://404dream.gitbook.io/mysql/summary/creating-and-using-a-database/retrieving-information-from-a-table/sorting-rows.md).

# 4.3.4.4 结果排序

您可能在前面的示例中注意到，结果行没有按特定顺序显示。当以某种有意义的方式对行进行排序时，通常更容易检查查询输出。要对结果排序，请使用ORDER BY子句。

这里是动物生日，按日期排序：

```
mysql>SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name     | birth      |
+----------+------------+
| Buffy    | 1989-05-13 |
| Bowser   | 1989-08-31 |
| Fang     | 1990-08-27 |
| Fluffy   | 1993-02-04 |
| Claws    | 1994-03-17 |
| Slim     | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy   | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+
```

在字符类型列上，排序（如所有其他比较操作）通常以不区分大小写的方式执行。这意味着对于除了它们的大小写之外的相同的列，未定义顺序。您可以使用BINARY强制对列进行区分大小写的排序，如：ORDER BY BINARY col\_name。

默认排序顺序是升序，最小值先。要按照相反（降序）顺序排序，请将DESC关键字添加到要排序的列的名称：

```
mysql>SELECT name, birth FROM pet ORDER BY birth DESC;

+----------+------------+
| name     | birth      |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy   | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim     | 1996-04-29 |
| Claws    | 1994-03-17 |
| Fluffy   | 1993-02-04 |
| Fang     | 1990-08-27 |
| Bowser   | 1989-08-31 |
| Buffy    | 1989-05-13 |
+----------+------------+
```

您可以对多个列进行排序，也可以按不同方向对不同列进行排序。例如，要按升序排列动物类型，然后按照动物类型中的出生日期降序（最小的动物首先），使用以下查询：

```
mysql>SELECT name, species, birth FROM pet
    ->ORDER BY species, birth DESC;
+----------+---------+------------+
| name     | species | birth      |
+----------+---------+------------+
| Chirpy   | bird    | 1998-09-11 |
| Whistler | bird    | 1997-12-09 |
| Claws    | cat     | 1994-03-17 |
| Fluffy   | cat     | 1993-02-04 |
| Fang     | dog     | 1990-08-27 |
| Bowser   | dog     | 1989-08-31 |
| Buffy    | dog     | 1989-05-13 |
| Puffball | hamster | 1999-03-30 |
| Slim     | snake   | 1996-04-29 |
+----------+---------+------------+
```

DESC关键字仅适用于紧接其前面的列名（birth）;它不影响物种列排序顺序。
