Sorting in SQL is a way to organize your query results in either ascending or descending order. The ORDER BY clause is used to sort the result set by one or more columns, making it easier to analyze data.
The basic syntax of the ORDER BY
clause is:
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Explanation:
- By default, ORDER BY
sorts in ascending order (ASC
).
- You can explicitly use ASC
for ascending order or DESC
for descending order.
- Multiple columns can be used for sorting, where the first column is the primary sort field and the subsequent columns act as secondary sorting fields.
Letβs assume we have a table named Employees with columns EmployeeID, Name, and Salary.
-- Sorting employees by Salary in ascending order SELECT * FROM Employees ORDER BY Salary;
This query will return all employees sorted by their Salary in ascending order.
If you want to sort the employees by their salary in descending order, you can use the DESC
keyword:
-- Sorting employees by Salary in descending order SELECT * FROM Employees ORDER BY Salary DESC;
This query sorts employees by their Salary from highest to lowest.
You can sort the result set by multiple columns. Letβs sort by Department and then by Salary:
-- Sorting employees by Department and then by Salary in descending order SELECT * FROM Employees ORDER BY Department, Salary DESC;
This query first sorts by Department alphabetically, and within each department, it sorts the employees by Salary in descending order.
Imagine you are managing an Orders table with the following columns:
Your task: Write an SQL query to sort the orders by OrderDate in ascending order and then by OrderAmount in descending order.
Write your ORDER BY
statement below:
ORDER BY
clause is the primary sorting criterion, and subsequent columns are used as secondary sorting keys.DESC
) can be explicitly specified.ORDER BY
on large tables.The ORDER BY clause is a versatile tool for sorting SQL results based on one or more columns. It helps you organize your data for better analysis and reporting. Remember to use it wisely to avoid performance issues when working with large datasets.
Quick Tip:
You can use ORDER BY
in combination with LIMIT
to restrict the number of rows returned. For example, ORDER BY OrderDate DESC LIMIT 5;
will give you the latest 5 orders.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!