Sorting Data According to More Than One Column in SQL
Last Updated :
31 Dec, 2024
In the world of relational databases, SQL is the essential tool for managing and manipulating data. One of the most fundamental operations in SQL is sorting data. While sorting by a single column is straightforward, sorting by multiple columns offers more control and flexibility.
In this article, we will explore multi-column sorting in SQL, complete with detailed examples, explanations, and best practices.
Multi-column Sorting
Multi-column sorting consists of organizing search results depending on the values from two or more columns. Let's take a database table containing employee records with columns such as Name, Department, and Salary as an example. Sorting only by Name might not be sufficient when multiple employees share the same name. In such cases, secondary sorting based on Department or Salary ensures that the results are meaningful and well-organized.
Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 ASC/DESC, column2 ASC/DESC, ...;
Key Terms
- ASC: Sorts the data in ascending order (default).
- DESC: Sorts the data in descending order.
Let’s go through some practical examples to understand how to apply multi-column sorting in SQL. We will use an Employees table with the following columns: Name, Department, and Salary.
Employees TableExample 1: Sorting by Department and Salary
This query sorts employees first by Department in ascending order. Within each department, it sorts by Salary in descending order.
Query:
SELECT Name, Department, Salary
FROM Employees
ORDER BY Department ASC, Salary DESC;
Output
Sorting by Department and SalaryExplanation:
- This query retrieves data from the Employees table, specifically the Name, Department, and Salary columns.
- It then sorts the results in ascending order based on the Department column and in descending order based on the Salary column.
Example 2: Sorting by Salary and Name within each Department
This query first sorts employees by Salary in descending order. If two employees have the same salary, the query further sorts them by Name in ascending order.
Query:
SELECT Name, Department, Salary
FROM Employees
ORDER BY Salary DESC, Name ASC;
Output
Sorting by Salary and Name within each DepartmentExplanation:
- This query retrieves data from the Employees table, specifically the Name, Department, and Salary columns.
- It then sorts the results in descending order based on the Salary column. If two employees have the same salary, it further sorts them in ascending order based on their Name.
Example 3: Sorting by Department, Salary, and Name
This query sorts the data first by Department in ascending order, then by Salary in descending order within each department. If two employees have the same salary, they are further sorted by Name in ascending order.
Query:
SELECT Name, Department, Salary
FROM Employees
ORDER BY Department ASC, Salary DESC, Name ASC;
Output
Sorting by Department, Salary, and NameExplanation:
- This query retrieves data from the Employees table, specifically the Name, Department, and Salary columns.
- It then sorts the results first in ascending order based on the Department column. Within each department group, it further sorts the employees in descending order based on their Salary.
- If two employees within the same department have the same salary, it finally sorts them in ascending order based on their Name.
Example 4: Sorting by Department in Descending Order, then by Salary in Ascending Order
This query sorts employees by Department in descending order. If two employees belong to the same department, they are sorted by Salary in ascending order.
Query:
SELECT Department, Salary
FROM Employees
ORDER BY Department DESC, Salary ASC;
Output
Sorting by Department in DESC, then by Salary in ASCExplanation:
- This query retrieves data from the Employees table, specifically the Department, and Salary columns.
- It then sorts the results in descending order based on the Department column. Within each department group, it further sorts the employees in ascending order based on their Salary.
Example 5: Sorting by Salary in Ascending Order, Nulls Last
This query sorts employees by Salary in ascending order, placing any NULL values at the end of the result set. NULLS LAST ensures that any rows with NULL salary values will appear at the bottom.
Query:
SELECT Name, Department, Salary
FROM Employees
ORDER BY Salary ASC NULLS LAST;
Output
Sorting by Salary in Ascending Order, Nulls LastExplanation:
- This query retrieves data from the Employees table, specifically the Name, Department, and Salary columns.
- It then sorts the results in ascending order based on the Salary column. Additionally, it specifies that NULL values in the Salary column should appear last in the sorted results.
Handling NULL Values
In SQL, when sorting by multiple columns, NULL values are handled based on the sorting order:
- By default, NULL values are sorted first in ascending order (ASC) and last in descending order (DESC).
- We can customize this behavior using NULLS FIRST or NULLS LAST.
Conclusion
In SQL, multi-column sorting allows us to organize our data efficiently by applying multiple levels of sorting criteria. By utilizing multi-column sorting, we can ensure that data is arranged in a hierarchy that fits our specific requirements. This can be particularly important in business contexts where decisions are based on a combination of criteria, such as sorting employees by Department, then by Salary, and finally by Name. mastering multi-column sorting not only improves the presentation of our data but also boosts the efficiency of our queries, making them more aligned with business needs.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read