How can I sort query results in ascending or descending order?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


In SQL, we use the ORDER BY keyword to sort the data in ascending or descending order, based upon any column or columns. By default, the sorting is done in ascending order. If you want to sort the results in descending order, you can use the DESC keyword. It’s a simple but powerful keyword that allows you to analyze your data more effectively, providing you with better insights.

The ORDER BY Keyword

The most common way to sort results in SQL is to use the ORDER BY keyword. This keyword sorts the records in ascending order by default. Here is a basic example of how you would use the ORDER BY keyword to sort the records in a table named ‘Employees’ by the ‘Name’ column:

This query will return a list of all records in the ‘Employees’ table, sorted by the ‘Name’ field in alphabetical order (from A to Z).

The DESC Keyword

If you want to sort your results in descending order, you can use the DESC keyword. Just append it after the column name in the ORDER BY clause. Here’s an example:

Now, this will sort the employee records in reverse alphabetical order (from Z to A).

Sorting by Multiple Columns

SQL also allows you to sort by multiple columns. This is useful when you have duplicate values in the column you are ordering by. In such cases, SQL will then sort these duplicates using the second column specified, and so on. Here’s an example:

This query will first sort the employees based on their names in ascending order, and in case of duplicate names, it will then sort those records by the ‘Salary’ field in descending order.

Conclusion

A powerful feature of SQL is its ability to organize data. Use the ORDER BY clause to sort your results in ascending or descending order, and gain valuable insights from your data. The language SQL is not only about fetching data, but it is also about analyzing data by logical sorting. Happy programming!

Leave a Comment