SQL ORDER BY DESC



SQL ORDER BY DESC

The SQL ORDER BY DESC clause is used to sort the result set of a query in descending order. This clause is essential for organizing data from the largest to smallest values, making it easier to analyze and understand.


Syntax

SELECT columns
FROM table_name
ORDER BY column1 DESC, column2 DESC, ...;

The DESC keyword sorts the records in descending order, from the largest to smallest values.


Example SQL ORDER BY DESC Queries

Let's look at some examples of SQL ORDER BY DESC queries using the employees table:

1. Basic ORDER BY DESC Example

SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date DESC;

This query retrieves the first name, last name, and hire date of employees, sorted by the hire_date column in descending order.

2. ORDER BY DESC with Multiple Columns

SELECT first_name, last_name, department_id, hire_date
FROM employees
ORDER BY department_id DESC, hire_date DESC;

This query retrieves the first name, last name, department ID, and hire date of employees, sorted first by the department_id column in descending order and then by the hire_date column in descending order.

3. ORDER BY DESC with Aliases

SELECT first_name AS FirstName, last_name AS LastName, hire_date AS HireDate
FROM employees
ORDER BY HireDate DESC;

This query retrieves the first name, last name, and hire date of employees with column aliases, sorted by the HireDate column in descending order.

4. ORDER BY DESC with Expressions

SELECT first_name, last_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;

This query retrieves the first name, last name, and annual salary (calculated as salary * 12) of employees, sorted by the annual_salary column in descending order.


Conclusion

The SQL ORDER BY DESC clause is a powerful tool for sorting query results in descending order. Understanding how to use the ORDER BY DESC clause and its syntax is essential for writing effective queries that organize data in a meaningful way, making it easier to analyze and interpret.