SQL ORDER BY Clause
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.
1. Overview
The ORDER BY
clause allows users to specify the sorting criteria for the rows returned by a query. It
can be applied to one or more columns, and the sorting can be done in ascending or descending order.
Example:
// Example of using the ORDER BY clause
SELECT *
FROM products
ORDER BY price DESC;
In this example, the ORDER BY
clause sorts the rows from the products
table based on the
price
column in descending order.
2. Syntax
The basic syntax of the ORDER BY
clause is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
The ASC
keyword is used to sort in ascending order (default), and the DESC
keyword is used
to sort in descending order.
3. Usage
To use the ORDER BY
clause, specify the column(s) to sort by after the ORDER BY
keyword in
an SQL statement.
Example:
// Example of using the ORDER BY clause with multiple columns
SELECT *
FROM employees
ORDER BY department ASC, salary DESC;
This example sorts the rows from the employees
table first by department
in ascending order
and then by salary
in descending order.
4. Conclusion
The SQL ORDER BY clause is a powerful feature for sorting query results in a specified order based on one or more columns. It allows users to customize the order in which data is displayed, providing greater control and flexibility in SQL queries.
Comments
Post a Comment