Sorting SQL data in ascending and descending order

Devanshu Agarwal

Written by Devanshu Agarwal /

As a SQL user, sorting data in a logical and organized way is essential for efficient data analysis. The ORDER BY clause in SQL allows users to sort data in either ascending or descending order based on their preferences. In this article, we will delve into how to sort data in ascending and descending order using the ORDER BY ASC or DESC clause, including sorting by multiple columns.

Let's see the table how it looks

Employees Table:

idnamedepartmentsalary
1John DoeMarketing5000
2Jane DoeMarketing6000
3Bob SmithHR4000
4Sarah LeeHR4500
5Tom ChenIT7000

Sorting SQL Data in Ascending Order Using ORDER BY ASC

To sort SQL data in ascending order, you can use the ORDER BY ASC clause. The ASC keyword specifies that the data should be sorted in ascending order. For instance, you can use the following SQL query to sort data in ascending order:

SQL
SELECT * FROM employees 
ORDER BY salary ASC;

This SQL query will sort the "employees" table by the "salary" column in ascending order.

Output

idnamedepartmentsalary
3Bob SmithHR4000
4Sarah LeeHR4500
1John DoeMarketing5000
2Jane DoeMarketing6000
5Tom ChenIT7000

Sorting SQL Data in Descending Order Using ORDER BY DESC

To sort SQL data in descending order, use the ORDER BY DESC clause. The DESC keyword specifies that the data should be sorted in descending order. Here's an example of sorting data in descending order:

SQL
SELECT * FROM employees 
ORDER BY salary DESC;

This query will sort the employees table by the salary column in descending order.

Output

idnamedepartmentsalary
5Tom ChenIT7000
2Jane DoeMarketing6000
1John DoeMarketing5000
4Sarah LeeHR4500
3Bob SmithHR4000

Sorting SQL Data by Multiple Columns

SQL data can also be sorted by multiple columns by adding more than one column to the ORDER BY clause. Here's an example of sorting data by multiple columns:

SQL
SELECT * FROM employees 
ORDER BY department, salary DESC;

This query will sort the employees table by the department column in ascending order first, and then by the salary column in descending order.

Output

idnamedepartmentsalary
4Sarah LeeHR4500
3Bob SmithHR4000
5Tom ChenIT7000
2Jane DoeMarketing6000
1John DoeMarketing5000

Conclusion

Sorting SQL data using the ORDER BY ASC or DESC clause is a crucial aspect of data analysis. It helps you to arrange your data in ascending or descending order as per your needs. Additionally, sorting by multiple columns further refines data analysis. Now that you have this knowledge, you can effectively sort and analyze your SQL data.