適用範圍
在Select 指令中,想進行謀資料做排序動作時使用
SELECT 欄位, 欄位, ...
FROM 資料表
Order by 欄位1,欄位2 ASC|DESC
SQL ORDER BY
在Select 指令將資料讀取後,想針對謀些欄位進行排列時,這時候就可使用 ORDER BY 指令來進行升序或降序的資料排序
ORDER BY 指令升序和降序:
- 升序(由大到小)使用 DESC
- 降序(由小到大)使用 ASC
透過客戶資料表查詢出料後,若要針對CustomerID 由大到小排序,則進行 ORDERB BY 欄位 DESC。
如果針對欄位進行由小到大 ,則可以不用填寫 ASC,指令可下 ORDER BY 欄位a
SELECT * FROM Customers ORDER BY CustomerID DESC;
CustomerID |
CompanyName |
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 Constitucion 2222 |
Mexico D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taqueria |
Antonio Moreno |
Mataderos 2312 |
Mexico D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbkop |
Christina Berglund |
Berguvsvagen 8 |
Lulea |
S-958 22 |
Sweden |
6 |
Blauer See Delikatessen |
Hanna Moos |
Forsterstr. 57 |
Mannheim |
68306 |
Germany |
7 |
Blondesddsl pere et fils |
Frederique Citeaux |
24, place Kleber |
Strasbourg |
67000 |
France |
8 |
Bolido Comidas preparadas |
Martin Sommer |
C/ Araquil, 67 |
Madrid |
28023 |
Spain |
9 |
Bon app' |
Laurence Lebihan |
12, rue des Bouchers |
Marseille |
13008 |
France |
10 |
Bottom-Dollar Markets |
Elizabeth Lincoln |
23 Tsawassen Blvd. |
Tsawassen |
T2F 8M4 |
Canada |
11 |
Du monde entier |
Janine Labrune |
67, rue des Cinquante Otages |
Nantes |
44000 |
France |
結果:
CustomerID |
CompanyName |
ContactName |
Address |
City |
PostalCode |
Country |
11 |
Du monde entier |
Janine Labrune |
67, rue des Cinquante Otages |
Nantes |
44000 |
France |
10 |
Bottom-Dollar Markets |
Elizabeth Lincoln |
23 Tsawassen Blvd. |
Tsawassen |
T2F 8M4 |
Canada |
9 |
Bon app' |
Laurence Lebihan |
12, rue des Bouchers |
Marseille |
13008 |
France |
8 |
Bolido Comidas preparadas |
Martin Sommer |
C/ Araquil, 67 |
Madrid |
28023 |
Spain |
7 |
Blondesddsl pere et fils |
Frederique Citeaux |
24, place Kleber |
Strasbourg |
67000 |
France |
6 |
Blauer See Delikatessen |
Hanna Moos |
Forsterstr. 57 |
Mannheim |
68306 |
Germany |
5 |
Berglunds snabbkop |
Christina Berglund |
Berguvsvagen 8 |
Lulea |
S-958 22 |
Sweden |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
3 |
Antonio Moreno Taqueria |
Antonio Moreno |
Mataderos 2312 |
Mexico D.F. |
05023 |
Mexico |
2 |
Ana Trujillo Emparedados y helados |
Ana Trujillo |
Avda. de la Constitucion 2222 |
Mexico D.F. |
05021 |
Mexico |
1 |
Alfreds Futterkiste |
Maria Anders |
Obere Str. 57 |
Berlin |
12209 |
Germany |
補充說明/ NOTE
除了欄位名外,也可使用欄位的順序。
於 SELECT 後的第一個欄位為 1,第二個欄位為 2,以此類推