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:
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:
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.
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:
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:
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!!