How to sort multiple columns using ORDER BY keyword in SQL
Overview
In SQL, we use the ORDER BY keyword to sort columns in ascending or descending order. The default is ascending order.
How does it work? It first sorts the first column, then the next, and the next, etc.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s);
Example
Let’s assume we have a Person table with columns such as name, age, state, and gender.
Now, we want to get the name and ages of people in the Person table in the order of their age and alphabetically by name.
How do we get this information from our table?
The following code shows how to use the ORDER BY keyword to sort multiple columns in SQL.
CREATE TABLE Person (ID int,name varchar(100),age int,gender varchar(10),state varchar(15));-- Insert dataINSERT INTO PersonVALUES (1,'Sharon Peller','16','Female','Kogi');INSERT INTO PersonVALUES (2,'Paul Dons','20','Male','Lagos');INSERT INTO PersonVALUES (3,'Ameera Abedayo','28','Female','Imo');INSERT INTO PersonVALUES (4,'Maria Elijah','25','Female','Lagos');INSERT INTO PersonVALUES (5,'David Hassan','30','Male','Abuja');INSERT INTO PersonVALUES (6,'Niniola Disu','28','Female','Lagos');INSERT INTO PersonVALUES (7,'Praise Dominion','26','Female','Abuja');INSERT INTO PersonVALUES (7,'Divine Favour','29','Female','Abuja');INSERT INTO PersonVALUES (7,'Praise Dominion','31','Female','Lagos');INSERT INTO PersonVALUES (8,'Joe Smith','16','Male','Lagos');-- QuerySELECT age, nameFROM PersonORDER BY age, name;
Explanation
- Lines 1–7: We create a
Persontable with columnsid,name,age,gender,andstate. - Lines 10–29: We insert data into the
Persontable. - Lines 31–35: We filter data based on some conditions using the
ORDER BYkeyword to sort the columns.