SQL ORDER BY

排序查詢結果

ORDER BY 可依欄位排序,升冪用 ASC,降冪用 DESC。實務上排序常和 TOP、LIMIT、排行榜報表搭配使用。

Example 1 - 多欄位排序

SELECT CustomerName, Country
FROM Customers
ORDER BY Country ASC, CustomerName ASC;

Example 2 - 價格由高到低

SELECT ProductName, Price
FROM Products
ORDER BY Price DESC;

Example 3 - 日期新到舊

SELECT OrderID, OrderDate
FROM Orders
ORDER BY OrderDate DESC;

Example 4 - 依計算欄位排序

SELECT ProductName, Price, Price * 1.05 AS TaxIncludedPrice
FROM Products
ORDER BY TaxIncludedPrice DESC;