SQL ORDER BY Multiple Columns

The ORDER BY clause can be applied to multiple columns to sort the result set based on more than one criterion. When multiple columns are used, the data is sorted first by the first column, and then by the subsequent columns if there are ties in the values of the first column.

Sorting by multiple columns is useful when you need to organize data hierarchically. For example, sorting employees by department and then by salary ensures the results are grouped by department and ordered by salary within each group.
Key points:

Example

This query sorts the products first by category in ascending order and then by price in descending order.

Code Example


-- Sort products by category (ascending) and price (descending)
SELECT Product, Category, Price
FROM Orders
ORDER BY Category ASC, Price DESC;
            

Output

Product Category Price
Laptop Electronics 1200.00
Phone Electronics 800.00
Tablet Gadgets 600.00

Explanation

- The query selects the Product, Category, and Price columns from the Orders table.
- The ORDER BY Category ASC ensures the products are sorted by category in alphabetical order, and the Price DESC further sorts the products within each category by price in descending order.

Sorting by multiple columns provides a refined and hierarchical view of the dataset, as shown in the output.