Back to cookbooks list Articles Cookbook

How to Order By Two Columns in SQL?

Problem:

You need to display records from a given table sorted by two columns.

Example:

Our database has a table named employee with the following columns: id, first_name, last_name, and salary.

idfirst_namelast_namesalary
1LisaUlman3000
2AdaMuller2400
3ThomasGreen2400
4MichaelMuller3000
5MaryGreen2400

Let’s display all information for each employee but sort the records according to salary in descending order first and then by last name in ascending order.

Solution:

SELECT id,  
  first_name,
  last_name,
  salary
FROM employee
ORDER BY salary DESC, last_name;

This query returns sorted records according to two columns: salary and last_name.

<
idfirst_namelast_namesalary
4MichaelMuller3000
1LisaUlman3000
3ThomasGreen2400
5MaryGreen2400
2AdaMuller2400

Discussion:

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.

After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column. If you want to use ascending (low to high) order, you can use the ASC keyword; this keyword is optional, though, as that is the default order when none is specified. If you want to use descending order, put the DESC keyword after the appropriate column (in the example, we used descending order for the salary column).

In our example, we first sorted the result by salary in descending order (higher salaries to lower ones) and then by last name in ascending order within those already sorted records.

Recommended courses:

Recommended articles:

See also: