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.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s);
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;
Person
table with columns id,
name,
age,
gender,
and state
.Person
table.ORDER BY
keyword to sort the columns.