ORDER BY ASC / DESC - SQL
In SQL, the ORDER BY clause is used to sort the result set returned by a query based on one or more columns. By default, the sorting order is ascending (ASC) for each column specified in the ORDER BY clause. However, users can also explicitly specify the sorting order as descending (DESC) for individual columns.
The syntax for using the ORDER BY clause with ASC and DESC keywords in SQL is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Where
- column1, column2, ...: Represents the columns used for sorting the result set.
- table_name: Specifies the name of the table from which data is retrieved.
- ASC or DESC: Specifies the sort order as ascending (ASC) or descending (DESC), respectively, for each column listed in the ORDER BY clause.
Example
Consider a scenario where you have a table named "employees" containing employee information, and you want to retrieve the employee data sorted by their salary in descending order and then by their hire date in ascending order. You can use the ORDER BY clause with DESC and ASC keywords as follows:
SELECT *
FROM employees
ORDER BY salary DESC, hire_date ASC;
In this example, the query retrieves all columns from the "employees" table and sorts the result set first by the "salary" column in descending order and then by the "hire_date" column in ascending order.
Conclusion
In SQL, the ASC and DESC keywords in the ORDER BY clause provide flexibility for specifying the sorting order (ascending or descending) for individual columns in the result set. By understanding their syntax, usage, and considerations, SQL developers can effectively control the sorting behavior to meet their specific requirements for data presentation and analysis.