The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. It allows you to specify the order in which the rows should be returned, either in ascending or descending order.
Key Points:
-
Sorting Order:
- By default,
ORDER BYsorts the data in ascending order (ASC). - You can specify descending order using the
DESCkeyword.
- By default,
-
Multiple Columns:
- You can sort by multiple columns by listing them in the
ORDER BYclause, separated by commas. The sorting will occur based on the first column, and if there are ties, it will sort by the second column, and so on.
- You can sort by multiple columns by listing them in the
-
Syntax:
SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Example:
Suppose you have a table named employees with columns name, department, and salary. Here are some examples of using ORDER BY:
-
Sort by Salary in Ascending Order:
SELECT * FROM employees ORDER BY salary; -
Sort by Salary in Descending Order:
SELECT * FROM employees ORDER BY salary DESC; -
Sort by Department and then by Salary:
SELECT * FROM employees ORDER BY department ASC, salary DESC;
In this example, the result set will first be sorted by the department column in ascending order, and within each department, it will be sorted by the salary column in descending order.
Using ORDER BY helps to organize the output of your queries, making it easier to analyze and interpret the data.
