SQL ORDER BY Keyword
Credit:  Image by Freepik
The SQL ORDER BY
keyword is used to sort the result set of a query based on one or more columns. It allows you to specify the sorting order, such as ascending (ASC
) or descending (DESC
).
Demo Database Tables
Let's consider five demo database tables to understand the usage of the ORDER BY
keyword:
1. Customers
CustomerID | CustomerName | Country |
---|---|---|
1 | John Doe | USA |
2 | Jane Smith | UK |
2. Orders
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 1 | 2022-01-15 |
2 | 2 | 2022-02-10 |
3. Products
ProductID | ProductName | Price |
---|---|---|
1 | Phone | 500 |
2 | Laptop | 1000 |
4. Employees
EmployeeID | EmployeeName | Salary |
---|---|---|
1 | John Smith | 5000 |
2 | Jane Johnson | 6000 |
5. Students
StudentID | StudentName | Age |
---|---|---|
1 | Michael Brown | 20 |
2 | Emily Davis | 22 |
Using the ORDER BY Keyword
To sort the result set based on a column, you can use the ORDER BY
keyword. Here are a few examples:
Example 1: Sorting Customers by Name in Ascending Order
SELECT * FROM Customers ORDER BY CustomerName ASC;
This query retrieves all columns from the "Customers" table and sorts the result by the "CustomerName" column in ascending order.
Example 2: Sorting Orders by Order Date in Descending Order
SELECT * FROM Orders ORDER BY OrderDate DESC;
This query retrieves all columns from the "Orders" table and sorts the result by the "OrderDate" column in descending order.
Example 3: Sorting Products by Price in Ascending Order
SELECT * FROM Products ORDER BY Price ASC;
This query retrieves all columns from the "Products" table and sorts the result by the "Price" column in ascending order.
Conclusion
The SQL ORDER BY
keyword allows you to sort the result set of a query based on one or more columns. By specifying the sorting order, you can retrieve the data in the desired sequence. Use the ORDER BY
keyword to organize and analyze your data effectively.
0 Comments