The ORDER BY
clause in SQL is used to sort the result set of a query in ascending or descending order based on one or more columns. It is often used with the SELECT
statement to present the data in a more organized and meaningful way.
4.3.1 Basic Syntax
The basic syntax of the ORDER BY
clause is as follows:
SELECT column1, column2, ...FROM table_nameORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
column1, column2, ...
: The columns you want to retrieve.table_name
: The name of the table.ORDER BY
: Specifies the sorting order.column1, column2, ...
: The columns by which the result set should be sorted.ASC
: Ascending order (default).DESC
: Descending order.
4.3.2 Example Queries
Consider a table named employees
with the following data:
emp_id | emp_name | emp_salary |
---|---|---|
1 | Alice | 50000 |
2 | Bob | 60000 |
3 | Charlie | 45000 |
4 | David | 70000 |
Example 1: Sorting in Ascending Order
SELECT emp_id, emp_name, emp_salaryFROM employeesORDER BY emp_salary ASC;
emp_id | emp_name | emp_salary |
---|---|---|
3 | Charlie | 45000 |
1 | Alice | 50000 |
2 | Bob | 60000 |
4 | David | 70000 |
Example 2: Sorting in Descending Order
SELECT emp_id, emp_name, emp_salaryFROM employeesORDER BY emp_salary DESC;
emp_id | emp_name | emp_salary |
---|---|---|
4 | David | 70000 |
2 | Bob | 60000 |
1 | Alice | 50000 |
3 | Charlie | 45000 |
4.3.3 Sorting by Multiple Columns
You can also sort the result set by multiple columns. Consider a table named sales
:
product_id | salesperson | sale_amount |
---|---|---|
1 | Alice | 200 |
2 | Bob | 150 |
1 | Charlie | 180 |
2 | Alice | 220 |
Example 3: Sorting by Multiple Columns
SELECT product_id, salesperson, sale_amountFROM salesORDER BY product_id, sale_amount DESC;
product_id | salesperson | sale_amount |
---|---|---|
1 | Charlie | 180 |
1 | Alice | 200 |
2 | Alice | 220 |
2 | Bob | 150 |
In this example, the result set is first sorted by product_id
in ascending order and then by sale_amount
in descending order.
The ORDER BY
clause is a powerful tool for organizing and presenting data in a way that best suits your needs. Experiment with different columns and sorting orders to refine your queries.