sql
  1. sql-order-by-desc

SQL ORDER BY DESC

The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. The DESC keyword is used with the ORDER BY clause to sort the result set in descending order. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using ORDER BY DESC in SQL.

Syntax

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

Example

Consider a table named employees with columns employee_id, employee_name, and salary. We want to retrieve the employee names and salaries in descending order of salary.

SELECT employee_name, salary
FROM employees
ORDER BY salary DESC;

Output

The output will display the employee names and salaries sorted in descending order of salary.

| employee_name | salary |
|---------------|--------|
| John          | 60000  |
| Alice         | 55000  |
| Bob           | 50000  |

Explanation

  • The ORDER BY clause is used to sort the result set.
  • salary DESC specifies that the result set should be sorted in descending order based on the salary column.

Use

The ORDER BY DESC in SQL is used for:

  • Sorting the result set in descending order based on one or more columns.
  • Retrieving the highest or most recent records from a table.
  • Organizing data for better analysis and reporting.

Important Points

  • DESC stands for "descending," and it reverses the default ascending order.
  • Multiple columns can be specified in the ORDER BY clause to perform sorting based on multiple criteria.

Summary

Sorting query results in descending order using ORDER BY DESC is a common operation in SQL. It allows for retrieving data in reverse order based on a specific column, providing flexibility in presenting data to users or performing analyses. Understanding how to use ORDER BY DESC is fundamental for creating meaningful and organized result sets in SQL queries.

Published on: