How to Order by Two Columns in SQL

Have you ever wanted to sort your data by two columns in SQL? It's a common task, and luckily, it's easy to do! In this post, we'll show you how to order by two columns in SQL and provide some examples to help you get started.

The Solution

The solution is to use the ORDER BY clause. This clause takes two arguments: the column you want to sort by and the direction of the sort (ascending or descending). For example, if you wanted to sort your data by the name column in ascending order, you would use the following query:

SELECT * FROM table_name ORDER BY name ASC;

If you wanted to sort by two columns, you would simply add a second argument to the ORDER BY clause. For example, if you wanted to sort by the name column in ascending order and then by the age column in descending order, you would use the following query:

SELECT * FROM table_name ORDER BY name ASC, age DESC;

Examples

Let's look at a few examples of how this clause can be used. Suppose you have a table called users with the following data:

users
nameage
John25
Jane30
John25
Bob20

If you wanted to sort this data by the name column in ascending order and then by the age column in descending order, you would use the following query:

SELECT * FROM users ORDER BY name ASC, age DESC;

This query would return the following result:

users
nameage
Bob20
John25
John25
Jane30

Additional Info

The ORDER BY clause is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database. 🤓

Want to build your own LLM Apps with AirOps👇👇