The SQL ORDER BY Keyword
ORDER BY keyword ใช้เพื่อจัดเรียงชุดผลลัพธ์ในลำดับจากน้อยไปมากหรือจากมากไปน้อย
ORDER BY keyword จะเรียงลำดับเรกคอร์ดจากน้อยไปมากตามค่าเริ่มต้น เมื่อต้องการเรียงลำดับเรกคอร์ดจากมากไปน้อย ให้ใช้ DESC คีย์เวิร์ด
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ฐานข้อมูลสาธิต
ด้านล่างนี้คือการเลือกจากตาราง “ลูกค้า” ในฐานข้อมูลตัวอย่าง Northwind:
CustomerID | CustomerName | 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 Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
ตัวอย่าง ORDER BY
คำสั่ง SQL ต่อไปนี้จะเลือกลูกค้าทั้งหมดจากตาราง “Customers” โดยจัดเรียงตามคอลัมน์ “Country”:
ตัวอย่าง
SELECT * FROM Customers
ORDER BY Country;
ตัวอย่าง ORDER BY DESC
คำสั่ง SQL ต่อไปนี้จะเลือกลูกค้าทั้งหมดจากตาราง “Customers” โดยเรียงลำดับจากมากไปน้อยตามคอลัมน์ “Country”:
ตัวอย่าง
SELECT * FROM Customers
ORDER BY Country DESC;
ตัวอย่าง ORDER BY Several Columns
คำสั่ง SQL ต่อไปนี้จะเลือกลูกค้าทั้งหมดจากตาราง “Customers” โดยจัดเรียงตามคอลัมน์ “Country” และ “CustomerName” ซึ่งหมายความว่าจะสั่งซื้อตาม Country แต่ถ้าบางแถวมี Country เดียวกัน จะสั่งซื้อตาม CustomerName:
ตัวอย่าง
SELECT * FROM Customers
ORDER BY Country, CustomerName;
ตัวอย่างที่ 2 ORDER BY Several Columns
คำสั่ง SQL ต่อไปนี้จะเลือกลูกค้าทั้งหมดจากตาราง “Customers” โดยเรียงลำดับจากน้อยไปหามากตาม “Country” และจากมากไปหาน้อยตามคอลัมน์ “CustomerName”:
ตัวอย่าง
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;