SELECT column_list
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
ASC(預設):升序DESC:降序NULL 值在升序中排最前,降序排最後沿用 Employee 表(8 筆資料,含 city、start_date 等欄位)。
SELECT * FROM employee ORDER BY city;
-- 結果:New York → Toronto → Vancouver(字母序)
+----+------------+-----------+------------+------------+---------+-----------+-------------+
| id | first_name | last_name | start_date | end_date | salary | city | description |
+----+------------+-----------+------------+------------+---------+-----------+-------------+
| 6 | Linda | Green | 1987-07-30 | 1996-01-04 | 4322.78 | New York | Tester |
| 7 | David | Larry | 1990-12-31 | 1998-02-12 | 7897.78 | New York | Manager |
| 1 | Jason | Martin | 1996-07-25 | 2006-07-25 | 1234.56 | Toronto | Programmer |
| 2 | Alison | Mathews | 1976-03-21 | 1986-02-21 | 6661.78 | Vancouver | Tester |
| 3 | James | Smith | 1978-12-12 | 1990-03-15 | 6544.78 | Vancouver | Tester |
| 4 | Celia | Rice | 1982-10-24 | 1999-04-21 | 2344.78 | Vancouver | Manager |
| 5 | Robert | Black | 1984-01-15 | 1998-08-08 | 2334.78 | Vancouver | Tester |
| 8 | James | Cat | 1996-09-17 | 2002-04-15 | 1232.78 | Vancouver | Tester |
+----+------------+-----------+------------+------------+---------+-----------+-------------+
SELECT * FROM employee ORDER BY city, start_date;
-- 同城市內按入職日期升序
-- New York 組:Linda(1987) → David(1990)
-- Vancouver 組:Alison(1976) → James(1978) → Celia(1982) → Robert(1984) → James(1996)
SELECT first_name, start_date FROM employee ORDER BY start_date;
+------------+------------+
| first_name | start_date |
+------------+------------+
| Alison | 1976-03-21 |
| James | 1978-12-12 |
| Celia | 1982-10-24 |
| Robert | 1984-01-15 |
| Linda | 1987-07-30 |
| David | 1990-12-31 |
| Jason | 1996-07-25 |
| James | 1996-09-17 |
+------------+
MySQL 日期型別(DATE/DATETIME/TIMESTAMP)天然支援正確排序,無需轉換。
SELECT first_name, salary FROM employee ORDER BY salary DESC;
+------------+---------+
| first_name | salary |
+------------+---------+
| David | 7897.78 |
| Alison | 6661.78 |
| James | 6544.78 |
| Linda | 4322.78 |
| Celia | 2344.78 |
| Robert | 2334.78 |
| Jason | 1234.56 |
| James | 1232.78 |
+------------+
-- 指定城市優先順序:Vancouver → Toronto → New York
SELECT * FROM employee
ORDER BY FIELD(city, 'Vancouver', 'Toronto', 'New York');
-- 或使用 CASE
ORDER BY CASE city
WHEN 'Vancouver' THEN 1
WHEN 'Toronto' THEN 2
WHEN 'New York' THEN 3
ELSE 4 END;
-- 按年薪(salary * 12)降序
SELECT first_name, salary, salary*12 AS annual
FROM employee
ORDER BY annual DESC;
SELECT * FROM employee ORDER BY RAND() LIMIT 3; -- 取 3 筆隨機樣本
ORDER BY 欄位若有索引,可避免 filesort,大幅提速SELECT 欄位 + ORDER BY 欄位 + WHERE 條件欄位組成複合索引最佳ORDER BY ... LIMIT N 可使用「優先隊列」優化,不需全量排序