×

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 Data Definition Language

Data definition language directly effects on the structure/schema of the database. CREATE, ALTER, DROP are the commands of DDL.CREATE: Creates new database, table, or view of table.ALTER: Modifies the database or...

3 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.

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 FULL JOIN

In this section, we will help you understand the concept of the SQL FULL Join clause with a few examples. The SQL FULL Join query is executed to display the integrated...

3 minutes read.

SQL Formatter

As a beginner, one does not focus much on Formatting the queries while writing their code. This leads to a great confusion while referring the code in future. For a...

5 minutes read.

SQL VIEW

The SQL VIEW concept helps to hide the difficulty of the records and provides limitations to access to the database. The SQL view is similar to the SQL tables. In SQL...

7 minutes read.

How to use LIKE in SQL

In this SQL article, we will learn and understand how to use LIKE to the columns in the SQL tables. What is Like? Like is an operator in the SQL. It is...

7 minutes read.

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 minutes read.

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,...

5 minutes read.

SQL SELECT AND Operator

This SQL tutorial explains and helps us understand how to use the AND Operator in the SELECT query with examples. The AND Operator is used to fetch the table’s records if...

2 minutes read.

SQL Aliases

SQL Aliases: These are used to give a temporary name for a column or table. These are used to make tables or columns more readable. These are used to rename the table...

2 minutes read.

SQL Injection

SQL injection is a technique, this may destroy the database. It is one type of hacking technique. SQL IN WEB PAGES: Injection occurs when we ask for input like an id or...

3 minutes read.

SQL CASE

This page contains all the information about SQL CASE. The CASE is an If-Else type of logical query used in the statement. The CASE in Structured Query Language is similar...

5 minutes read.

SQL SET Operator

In this tutorial, we will understand the operator who falls under the SET operator in SQL with the help of different examples. The SQL SET Operator is used to merge the...

5 minutes read.

SQL Except

In SQL, we probably use the JOIN clause to receive the combined result from one or more than one table. But sometimes, we want a result that contains data from...

4 minutes read.

SQL SELECT LIKE Operator

The SQL SELECT LIKE Operator tutorial helps us understand how to use the LIKE operator in the SELECT query with examples. The SQL SELECT LIKE Operator retrieves the records from the...

4 minutes read.

SQL SELECT BETWEEN Operator

This SQL tutorial explains and helps us understand how to use the BETWEEN operator in the SELECT query with examples. The SQL SELECT BETWEEN operator retrieves the data from the table...

2 minutes read.

SQL Temporary Tables

Temporary Table: The Temporary tables are generally created in TempDB. If the last connection is terminated then the tables are deleted automatically. These are generally used to store and process the...

4 minutes read.

Save Point in SQL

In SQL, the classification is done into 4 languages. They are Data Definition Language (DDL)Data Manipulation Language (DML)Transaction Control Language (TCL)Data Control Language (DCL) Save Point falls under the Transaction Control Language....

4 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.