SQL Standard

SQL Order By Multiple Columns

This article will discuss how you can order data by multiple columns. Ordering by multiple columns is only applicable to the SELECT statement.

Let us discuss.

Syntax

To order data by multiple columns, we can express the query as shown in the syntax below:

select col_1, col_2, col_3, ..., col_N
from table_name
[where condition]
order by col_1, col_2, ... col_N asc|desc

Let us see how we can use the above syntax in a table.

Let us assume we have an example table as shown in the query below:

create table users(

id serial primary key,

first_name varchar(100),

last_name varchar(100),

state varchar(25),

active bool

);

insert into users(first_name, last_name, state, active) values (

'Mary', 'Smith', 'New York', TRUE);

insert into users(first_name, last_name, state, active) values (

'Linda', 'Williams', 'Colorado', FALSE);

insert into users(first_name, last_name, state, active) values (

'Taylor', 'Moore', 'Utah', TRUE);

insert into users(first_name, last_name, state, active) values (

'Susan', 'Wilson', 'Washington', TRUE);

insert into users(first_name, last_name, state, active) values (

'Mary', 'Smith', 'New York', TRUE);

insert into users(first_name, last_name, state, active) values (

'Taylor', 'Moore', 'Utah', TRUE);

Once we have the table and sample data added to the table, we can proceed.

For example, let us order by first_name and state columns.

select id, first_name, last_name, state, active

from users

order by first_name asc, state desc;

We sort the result by first_name in ascending order and state by descending order in the query above.

The query above should return:

Keep in mind that sorting data by multiple columns might be beneficial. On the other hand, you might suffer significant performance charges in large databases.

To sort multiple columns in ascending order, we can do:

select id, first_name, last_name, state, active

from users

order by first_name asc, last_name asc;

In this case, we sort the first_name and last_name columns in ascending order. This should return:

To sort in descending order, run the query as:

select id, first_name, last_name, state, active

from users

order by first_name desc, last_name desc;

This should return:

Conclusion

This tutorial explores using SQL to sort data from a result via multiple columns.

Thank you for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list