Friday, September 22, 2023

How do you sort results in descending order?

To sort results in descending order in SQL, you use the ORDER BY clause along with the DESC keyword. The ORDER BY clause is used to specify the column or columns by which you want to sort your query results, and the DESC keyword is added to indicate that you want the sorting to be in descending order.

Here's how you can do it:


SELECT column1, column2 
FROM table_name
ORDER BY column_to_sort DESC;
  • SELECT: Specifies the columns you want to retrieve in the query result.
  • FROM: Specifies the table from which you want to retrieve data.
  • ORDER BY: Specifies the column by which you want to sort the results.
  • DESC: Indicates that you want to sort the results in descending order.

Here's an example of how you can use ORDER BY and DESC to sort query results in descending order:

SELECT product_name, price 
FROM products 
ORDER BY price DESC;

In this example, the SQL statement retrieves the product names and prices from the "products" table and sorts the results by the "price" column in descending order. As a result, the products with the highest prices will appear first in the query results.

You can also sort by multiple columns and specify the sort order (ascending or descending) for each column in the ORDER BY clause. For example:

SELECT product_name, category, price 
FROM products 
ORDER BY category ASC, price DESC;

In this case, the results are first sorted in ascending order by the "category" column, and within each category, they are sorted in descending order by the "price" column.

Keep in mind that if you don't specify ASC or DESC, the default sort order is ascending (ASC). So, if you want to sort in descending order, make sure to include DESC after the column you want to sort by. 

No comments:

Post a Comment

If you have any doubts. Please let me know

How can you create an alias for a table in a SQL query?

In SQL, you can create an alias for a table in a query to give the table a temporary, alternative name that you can use in the query. Table ...