The ORDER BY keyword in SQL is used to sort the result set of a query by one or more columns, either in ascending or descending order. By default, ORDER BY sorts the data in ascending order (ASC), but it can also be explicitly set to descending order (DESC).
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
column1, column2, ...: The columns by which you want to sort the result.ASC: Sorts the result in ascending order (default if not specified).DESC: Sorts the result in descending order.
Example 1: Sorting in Ascending Order (Default)
SELECT first_name, last_name, age
FROM employees
ORDER BY age;
This query will sort the employees by their age in ascending order (youngest to oldest).
Example 2: Sorting in Descending Order
SELECT first_name, last_name, age
FROM employees
ORDER BY age DESC;
This query will sort the employees by their age in descending order (oldest to youngest).
Example 3: Sorting by Multiple Columns
You can also sort by multiple columns. In this case, the results are first sorted by the first column and then by the second, if there are ties.
SELECT first_name, last_name, age
FROM employees
ORDER BY age DESC, last_name ASC;
This query will:
- Sort by age in descending order.
- If two or more employees have the same age, they will be sorted by last name in ascending order.
Notes:
- The
ORDER BYclause must be placed at the end of a query. - The default sorting is in ascending order (
ASC), so you can omitASCwhen it is not needed. - You can sort by expressions, aliases, or even functions.
Example with an Expression:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary * 1.1 DESC;
This query sorts employees by their projected salary (after a 10% increase) in descending order.
The ORDER BY clause is a powerful tool to organize the data in the desired format, helping to make reports, analyses, or even user interface results more readable.
No comments:
Post a Comment