SQL ORDER BY Keyword


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:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden


ตัวอย่าง 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;