How do you sort results by multiple columns in SQL?

NicolasBrondinBernard

Author
@NicolasBrondinBernard

Need to sort data by multiple fields in SQL? It's possible with ORDER BY!

Article published on 04/12/2023, last updated on 10/08/2026

Do you need to order the rows returned by your query using several different columns?

It's very simple.

In SQL, you can simply list as many fields as you want in the ORDER BY clause, separating them with commas.

Example

Let's imagine that we want to sort our users by age, but we also want to sort them alphabetically for all those having the same age.

Here's the query you'll need to write:

SELECT 
  id,   
  firstname,
  lastname,   
  age
FROM User
ORDER BY age DESC, lastname ASC;

Note that the first columns in the ORDER BY take priority, unlike the implementation of chained sorting in classic programming!


Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet