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 data INSERT INTO Person VALUES (1,'Sharon Peller','16','Female','Kogi'); INSERT INTO Person VALUES (2,'Paul Dons','20','Male','Lagos'); INSERT INTO Person VALUES (3,'Ameera Abedayo','28','Female','Imo'); INSERT INTO Person VALUES (4,'Maria Elijah','25','Female','Lagos'); INSERT INTO Person VALUES (5,'David Hassan','30','Male','Abuja'); INSERT INTO Person VALUES (6,'Niniola Disu','28','Female','Lagos'); INSERT INTO Person VALUES (7,'Praise Dominion','26','Female','Abuja'); INSERT INTO Person VALUES (7,'Divine Favour','29','Female','Abuja'); INSERT INTO Person VALUES (7,'Praise Dominion','31','Female','Lagos'); INSERT INTO Person VALUES (8,'Joe Smith','16','Male','Lagos'); -- Query SELECT age, name FROM Person ORDER BY age, name;
Person
table with columns id,
name,
age,
gender,
and state
.Person
table.ORDER BY
keyword to sort the columns.RELATED TAGS
CONTRIBUTOR
View all Courses