×

SQL ORDER BY

SQL ORDER BY

The SQL ORDER BY clause is used to sort the data stored in tables in the database. The sorting can be done in an ascending way, descending way, or based on multiple columns of the table.

Generally, the default sorting order is ascending order.

SELECT expressions
 FROM tables
 WHERE conditions
 ORDER BY expression ASC | DESC; 

The following is the syntax of a general ORDER BY clause:

Example:

Let’s consider the following Customers table.

IDNAMEAGEADDRESSSALARY
1Himani gupta21Modinagar22000
2Shiva tiwari22Bhopal21000
3Ajeet bhargav45Meerut65000
4Ritesh yadav36Azamgarh26000
5Balwant singh45Varanasi36000
6Mahesh sharma26Mathura22000
 SELECT * 
 FROM Customers
 ORDER BY NAME, SALARY; 

The above query will sort all the records in ascending order based on the NAME and SALARY columns.

Output:

IDNAMEAGEADDRESSSALARY
3Ajeet bhargav45Meerut65000
5Balwant singh45Varanasi36000
1Himani gupta21Modinagar22000
6Mahesh sharma26Mathura22000
4Ritesh yadav36Azamgarh26000
2Shiva tiwari22Bhopal21000
SELECT *
 FROM CUSTOMERS
 ORDER BY NAME DESC; 

The above query will sort all the records in the table in a descending manner based on the NAME column.

Output:

IDNAMEAGEADDRESSSALARY
2Shiva tiwari22Bhopal21000
4Ritesh yadav36Azamgarh26000
6Mahesh sharma26Mathura22000
1Himani gupta21Modinagar22000
5Balwant singh45Varanasi36000
3Ajeet bhargav45Meerut65000

There are various topics under SQL ORDER BY clause. Namely, they are:

  • SQL ORDER BY ASC – Sorts the data in ascending manner
  • SQL ORDER BY DESC – Sorts the data in descending manner
  • SQL ORDER BY RANDOM – Sorts random data
  • SQL ORDER BY LIMIT – Selects limited data from the database
  • SQL ORDER BY Multiple Columns – Sorts the data based on multiple columns.

Let’s discuss each of them in detail.

SQL ORDER BY ASC

SQL ORDER BY ASC clause sorts the data in ascending order based on some columns. Generally, the default sorting order is ascending manner.

Example:

Let’s consider the following Customers table.

IDNAMEAGEADDRESSSALARY
1Himani gupta21Modinagar22000
2Shiva tiwari22Bhopal21000
3Ajeet bhargav45Meerut65000
4Ritesh yadav36Azamgarh26000
5Balwant singh45Varanasi36000
6Mahesh sharma26Mathura22000
SELECT * 
 FROM Customers
 ORDER BY NAME, SALARY; 

The above query will sort all the records in ascending order based on the NAME and SALARY columns.

Output:

IDNAMEAGEADDRESSSALARY
3Ajeet bhargav45Meerut65000
5Balwant singh45Varanasi36000
1Himani gupta21Modinagar22000
6Mahesh sharma26Mathura22000
4Ritesh yadav36Azamgarh26000
2Shiva tiwari22Bhopal21000

SQL ORDER BY DESC

SQL ORDER BY DESC clause sorts the data in descending order based on some columns.

Example:

Let’s consider the following Customers table.

IDNAMEAGEADDRESSSALARY
1Himani gupta21Modinagar22000
2Shiva tiwari22Bhopal21000
3Ajeet bhargav45Meerut65000
4Ritesh yadav36Azamgarh26000
5Balwant singh45Varanasi36000
6Mahesh sharma26Mathura22000
SELECT *
 FROM CUSTOMERS
 ORDER BY NAME DESC; 

The above query will sort all the records in the table in a descending manner based on the NAME column.

Output:

IDNAMEAGEADDRESSSALARY
2Shiva tiwari22Bhopal21000
4Ritesh yadav36Azamgarh26000
6Mahesh sharma26Mathura22000
1Himani gupta21Modinagar22000
5Balwant singh45Varanasi36000
3Ajeet bhargav45Meerut65000

SQL ORDER BY LIMIT

The SQL ORDER BY LIMIT clause helps in retrieving specific number of records from the database table. It is generally used in situations where there are large number of tuples which satisfy the given condition. It sets an upper limit to the number of records that are being retrieved.

In order to use the LIMIT clause in SQL, one has to use the ROWNUM clause with it.

Note: It should be noted that the LIMIT clause is not supported by all SQL versions.

This clause can be specified using the SQL 2008 OFFSET or FETCH FIRST clauses.

Example:

Let’s consider the following Student table.

RollNoNameGrade
12001Aditya9
12002Sahil6
12003Hema8
12004Robin9
12005Sita7
12006Anne10
12007Yusuf7
12008Alex5
SELECT *
 FROM Student
 LIMIT 5; 

The above query will only return the top 5 students from the Student table.

Output:

12001Aditya9
12002Sahil6
12003Hema8
12004Robin9
12005Sita7

The LIMIT clause can also be used with the ORDER BY clause.

SELECT *
 FROM Student
 ORDER BY Grade DESC
 LIMIT 3; 

The above query will return the top 3 students having the highest grades in descending order.

Output:

12006Anne10
12001Aditya9
12004Robin9

The LIMIT operator is especially useful in situations where limited data needs to be retrieved without using any conditional statements.

The LIMIT operator can also be used with the OFFSET operator.

LIMIT with OFFSET

It is to be noted that the OFFSET value should be greater than zero, and it cannot be negative. If a negative value is supplied, it will return an error.

Example:

Let’s consider the same Student table.

RollNoNameGrade
12001Aditya9
12002Sahil6
12003Hema8
12004Robin9
12005Sita7
12006Anne10
12007Yusuf7
12008Alex5
SELECT *
FROM Student
LIMIT 5 OFFSET 2
ORDER BY RollNo;

This query will return the top 5 records of the Student table excluding the top 2 entries.

Output:

RollNoNameGrade
12003Hema8
12004Robin9
12005Sita7
12006Anne10
12007Yusuf7

LIMIT ALL

There is another clause similar to LIMIT known as LIMIT ALL. The LIMIT ALL clause will not put any limit and will return all the entries of the table.

Example:

Let’s again consider the same Student table.

RollNoNameGrade
12001Aditya9
12002Sahil6
12003Hema8
12004Robin9
12005Sita7
12006Anne10
12007Yusuf7
12008Alex5

Query:

SELECT *
FROM Student
LIMIT ALL;
RollNoNameGrade
12001Aditya9
12002Sahil6
12003Hema8
12004Robin9
12005Sita7
12006Anne10
12007Yusuf7
12008Alex5

SQL ORDER BY Multiple Columns

The SQL ORDER BY Multiple Columns will return the data entries in the column by sorting them using multiple columns which have been given in the query.

It will sort the data based on the order of the column names which have been supplied after the ORDER BY clause. The name of the columns should be added in the corresponding order in which the user wants the sorting to happen.

Multiple column names can be added by separating them using a comma (,). Also, the ASC or DESC keywords can be used to specify the order of the sorting.

Example:

Let’s consider the following Employee table having four columns namely id, first_name, last_name, and salary.

idfirst_namelast_namesalary
1LisaUlman3000
2AdaMuller2400
3ThomasGreen2400
4MichaelMuller3000
5MaryGreen2400

Query:

SELECT id,  
 first_name,
 last_name,
 salary
 FROM employee
 ORDER BY salary DESC, last_name; 

Output:

idfirst_namelast_namesalary
4MichaelMuller3000
1LisaUlman3000
3ThomasGreen2400
5MaryGreen2400
2AdaMuller2400

Hence, first, the output has been sorted by salary in descending order and then by last name in ascending order. It is to be noted that if ASC or DESC is not mentioned, it will, by default, sort the both the columns in ascending order.

Conclusion

So, above are some of the most important and frequently used ORDER BY clauses that are used by developers daily in order to perform specific operations on the database and retrieve out data. These clauses can be used individually or they can also be used together, in a combined way, to carry out database operations.


Related Topics

SQL CONSTRAINTS

SQL Constraints specifies the rules/limitations/restrictions for data present in table. SQL Constraints are specified at the time of table creation or after table creation using ALTER command. There are two...

5 minutes read.

SQL INTERSECT

SQL intersect operator is used to combine two or more SELECT statements, but it only displays the data similar to the SELECT statement. The syntax for the INTERSECT operation: SELECT COLUMN_NAME1, COLUMN_NAME2,...

3 minutes read.

DML Commands in SQL

DML is an abbreviation of Data Manipulation Language. Data Manipulation Language commands in Structured Query Language manipulate the data in the database. DML commands are used to retrieve records, add records,...

4 minutes read.

SQL UPDATE

SQL UPDATE The SQL UPDATE statement is utilized to update and modify the records present into a database. It is used to change the already existing records stored in the tables...

3 minutes read.

How to compare date in SQL

In this section, we will learn about how dates can be compared in SQL. We can compare any random date with another date stored in a column of a table.This comparison...

4 minutes read.

SQL INSERT INTO SELECT

In this tutorial, we will help you to understand and learn how to copy records from one table and add them to another table in the SQL with the help...

5 minutes read.

SQL WHERE Multiple Conditions

In this topic, we will learn how to add multiple conditions using the WHERE clause. First, let's understand the concept of WHERE clause. WHERE clause is used to specify a condition while...

5 minutes read.

How to create a database in SQL?

How to create a database in SQL It is very necessary to create a database in order to store the data into the database.Database name must always be unique.SQL does not...

6 minutes read.

How to delete column in table

Introduction In SQL, sometimes it is required to delete a column of a table.The use of ALTER TABLE command with DROP COLUMN clause will serve the purpose to delete/remove a column...

4 minutes read.

How to add column in table in SQL ?

How to add column in table in SQL  Introduction To add a column in already created table, one needs to use the ALTER command along with the ADD clause.If in the query,...

7 minutes read.

SQL Between Operator

SQL Between operator is a logical operator in the Structured Query Language. The Between operator is used to retrieve data within the range specified in the condition in the query. The...

7 minutes read.

SQL SELECT MAX

The SQL Max() function is an aggregate function in SQL. This function returns the values which are greater in the condition. The condition may be a number, or it may...

5 minutes read.

Trigger in SQL

In this article, we will learn about the concept of trigger in SQL and its implementation with the help of an example. A Trigger in Structured Query Language is a set...

4 minutes read.

Difference between SQL and NoSQL

SQL vs. NoSQL | Difference between SQL and NoSQL Choosing a database is the most fundamental decision that needs to be decided before starting a task. Relational and non-relational databases are...

3 minutes read.

DELETE VS DROP in SQL

This page contains all the information about the Delete command and Drop command concept and the difference between the DELETE and DROP commands in SQL. What is the DELETE command in...

3 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

SQL SELECT Database

In this tutorial, we will help you to understand and learn how to select the database in SQL with the help of examples. The database user or the administrator wants to...

3 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

Types of SQL Commands

The Structured Query Language is used to deal with structured data. The data which are stored in the form of tables are structured data. These SQL commands store records or...

10 minutes read.

SQL WHERE Statement

SQL WHERE Statement Introduction WHERE clause is used to include a condition while fetching data from tables.When you have to specify a condition that has to be obeyed while data is...

9 minutes read.