Wednesday, December 18, 2024

SQL DESC Keyword

 The SQL DESC keyword is used primarily in two different contexts:

1. For Describing a Table Structure (DESC command)

The DESC (or DESCRIBE) keyword is used to display the structure of a database table. It shows the column names, data types, whether the columns can hold NULL values, and other constraints like primary keys.

Syntax:

DESC table_name;

Or,

DESCRIBE table_name;

Example:

DESC employees;

This would show the structure of the employees table, including the names and data types of all the columns.

2. For Sorting Results in Descending Order (DESC in ORDER BY clause)

The DESC keyword is also used to sort the result set in descending order when combined with the ORDER BY clause. It ensures that the values in the sorted column are displayed from highest to lowest.

Syntax:

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

Example:

SELECT name, salary
FROM employees
ORDER BY salary DESC;

In this case, the results will show the name and salary of employees, sorted in descending order by the salary column, so that the highest salary appears first.

Summary:

  • DESC as part of DESCRIBE or DESC command is used to view the structure of a table.
  • DESC as part of the ORDER BY clause is used to sort query results in descending order.

No comments:

Post a Comment