SQL – Multiple Column Ordering
SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQl commands like ‘select’, ‘delete’, ‘alter’ etc. For column ordering in SQL, we use the ‘ORDER BY’ keyword.
It is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
SELECT * FROM table_name ORDER BY column_name;
For Multiple column order, add the name of the column by which you’d like to sort records first. The column that is entered at first place will get sorted first and likewise.
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks:
Step 3: Table definition
We have the following demo_table in our geeks database.
CREATE TABLE geeksforgeeks( FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(20), CITY VARCHAR(20), AGE INT, GENDER VARCHAR(20));
Step 4: Insert data into the table
INSERT INTO geeksforgeeks VALUES ('ROMY', 'Kumari', 'New Delhi', 22, 'female'), ('Pushkar', 'jha', 'New Delhi', 23, 'male'), ('Sujata', 'jha', 'Bihar', 30, 'female'), ('Roshini', 'Kumari', 'Bihar', 16, 'female'), ('Avinav', 'Pandey', 'New Delhi', 21, 'male'), ('Aman','Dhattarwal','Banglore', 30, 'male'), ('Aman','Agnihotri','Chennai', 23, 'male'), ('Aman','Malik','Agra', 35, 'male'), ('Bhawna','Dhattarwal','Banglore', 34, 'female'), ('Bhawna','Meena','Rajastha', 30, 'female')
Step 5: To see the content of the table
SELECT * FROM geeksforgeeks;
Let’s take an example to order table content based on firstname and then on age.
SELECT * FROM geeksforgeeks ORDER BY FIRSTNAME, AGE;
Now if we want to Order by firstname (ascending), lastname(descending), age(descending) then the query is:
SELECT * FROM geeksforgeeks ORDER BY FIRSTNAME, LASTNAME DESC, AGE DESC ;
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.