Skip to content
Related Articles

Related Articles

Improve Article

SQL – Multiple Column Ordering

  • Last Updated : 14 Sep, 2021

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.

Order By:

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.

Syntax:

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:



Query:

CREATE DATABASE geeks;

Step 2:  Using the Database

Use the below SQL statement to switch the database context to geeks:

Query:

USE geeks;

Step 3:  Table definition

We have the following demo_table in our geeks database.

Query:

 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 

Query:



SELECT * FROM geeksforgeeks;

Output:

Let’s take an example to order table content based on firstname and then on age.

Query:

 SELECT * FROM geeksforgeeks ORDER BY FIRSTNAME, AGE;

Output:

Now if we want to Order by firstname (ascending), lastname(descending), age(descending) then the query is: 

Query:

 SELECT * FROM geeksforgeeks ORDER BY FIRSTNAME, LASTNAME DESC, AGE DESC ;

Output:

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

My Personal Notes arrow_drop_up
Recommended Articles
Page :