The Wayback Machine - https://web.archive.org/web/20240605022329/https://www.geeksforgeeks.org/sql-order-by/
Open In App

SQL ORDER BY

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

SQL ORDER BY clause sorts the result of the SELECT statement either in ascending or descending order.

In this article, we’ll explore the ORDER BY clause, exploring its syntax, functionality, and usage with detailed examples.

ORDER BY in SQL

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. It is very useful to present data in a structured manner.

SQL ORDER BY default mode is sorting data into ascending order. To sort data in descending order use the DESC keyword with ORDER BY clause.

Syntax

The syntax to use ORDER BY clause in SQL is:

SELECT * FROM table_name ORDER BY column_name ASC | DESC

Key Terms:

  • table_name: name of the table.
  • column_name: name of the column according to which the data is needed to be arranged.
  • ASC: to sort the data in ascending order.
  • DESC: to sort the data in descending order.

SQL ORDER BY Clause Examples

Let’s look at some examples of the SQL ORDER BY clause to understand it’s working in SQL.

We will use the following table in examples.

demo sql table

Student_Table

To create this table, write the following SQL queries:

SQL
CREATE TABLE students (
  roll_no INT NOT NULL,
  age INT NOT NULL,
  name VARCHAR(50) NOT NULL,
  address VARCHAR(100) NOT NULL,
  phone VARCHAR(20) NOT NULL,
  PRIMARY KEY (roll_no)
);
INSERT INTO students (roll_no, age, name, address, phone)
VALUES 
  (1, 18, 'Shubham Thakur', '123 Main St, Mumbai', '9876543210'),
  (2, 19, 'Aman Chopra', '456 Park Ave, Delhi', '9876543211'),
  (3, 20, 'Naveen Tulasi', '789 Broadway, Ahmedabad', '9876543212'),
  (4, 21, 'Aditya arpan', '246 5th Ave, Kolkata', '9876543213'),
  (5, 22, 'Nishant Jain', '369 3rd St, Bengaluru', '9876543214')

Now consider the above database table and find the results of different queries.

Sort According To a Single Column using ORDER BY Clause Example

In this example, we will fetch all data from the table Student and sort the result in descending order according to the column ROLL_NO. 

Query:

SELECT * FROM students ORDER BY ROLL_NO DESC;

Output:

sort according to a single column using order by clause example output

In the above example, if we want to sort in ascending order we have to use ASC in place of DESC.

Sort According To Multiple Columns using ORDER BY Clause Example

To sort according to multiple columns, separate the names of columns by the (,) operator. 

Syntax:

SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC

In this example, we will fetch all data from the table Student and then sort the result in descending order first according to the column age. and then in ascending order according to the column name. 

Query:

SELECT * FROM students ORDER BY age DESC , name ASC;

Output:

sort according to multiple columns using order by clause example output

Sort_Multiple_Column

In the above output, we can see that first the result is sorted in descending order according to Age. There are multiple rows of having the same Age. Now, sorting further this result-set according to name will sort the rows with the same Age according to name in ascending order.

Note:

ASC is the default value for the ORDER BY clause. So, if we don’t specify anything after the column name in the ORDER BY clause, the output will be sorted in ascending order by default. 

Sorting By Column Number (instead of name)

An integer that identifies the number of the column in the SelectItems in the underlying query of the SELECT statement. Column number must be greater than 0 and not greater than the number of columns in the result table. In other words, if we want to order by a column, that column must be specified in the SELECT list.

The rule checks for ORDER BY clauses that reference select list columns using the column number instead of the column name. The column numbers in the ORDER BY clause impair the readability of the SQL statement. Further, changing the order of columns in the SELECT list has no impact on the ORDER BY when the columns are referred to by names instead of numbers. 

Syntax

The Syntax to use ORDER BY Clause with Column Number

ORDER BY Column_Number asc/desc

Sorting By Column Number Example

Here we take an example to sort a database table according to column 1 i.e Name. For this a query will be:

Query:

CREATE TABLE studentinfo
( Roll_no INT,
NAME VARCHAR(25),
Address VARCHAR(20),
CONTACTNO BIGINT NOT NULL,
Age INT ); 

INSERT INTO studentinfo
VALUES (7,'ROHIT','GHAZIABAD',9193458625,18),
(4,'DEEP','RAMNAGAR',9193458546,18),
(1,'HARSH','DELHI',9193342625,18),
(8,'NIRAJ','ALIPUR',9193678625,19),
(5,'SAPTARHI','KOLKATA',9193789625,19),
(2,'PRATIK','BIHAR',9193457825,19),
(6,'DHANRAJ','BARABAJAR',9193358625,20),
(3,'RIYANKA','SILIGURI',9193218625,20);

SELECT Name, Address
FROM studentinfo
ORDER BY 1

Output:

output

output

Explanation:

ORDER BY 1 means sorting values according to first column in the SELECT statement.

Important Points About ORDER BY Clause in SQL

  • The ORDER BY clause in SQL is used to sort the result set of a SELECT statement based on specified columns.
  • It is essential for organizing query results and presenting data in a structured manner.
  • It can sort data in either ascending (ASC) or descending (DESC) order.
  • Multiple columns can be specified for sorting, allowing for more complex sorting criteria.
  • We can use ORDER BY with WHERE clause, GROUP BY clause, and HAVING clause.


Previous Article
Next Article

Similar Reads

Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
Order by in MS SQL Server
In this article, order by and terms related to order by will be discussed. Introduction - There are some instances where the tables are to be arranged in a chronological order. While the users use the select statement to retrieve rows, one cannot guarantee that the rows are arranged in an order. To solve this, order by clause is being used. Basic s
2 min read
Using CASE in ORDER BY Clause to Sort Records By Lowest Value of 2 Columns in SQL
In this article, we will see how to use CASE in the ORDER BY clause to sort records by the lowest value of 2 columns in SQL. CASE statement: This statement contains one or various conditions with their corresponding result. When a condition is met, it stops reading and the corresponding result gets returned (similar to the IF-ELSE statement). It re
2 min read
How to Custom Sort in SQL ORDER BY Clause?
By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted. In this article let us see how we can custom sort in a table using order by using MSS
2 min read
How to Use SELECT In Order BY Specific Ids in SQL?
The order by the statement is used in SQL to sort the result set in ascending or descending by mentioning it in the suffix as DESC (for descending) and for ASC(for ascending). In this article, we will be doing order by on a database with some specified values of the column only. So let's start by creating a Database first. Step 1: Create a database
1 min read
SQL Use ORDER BY With TOP to Return the Top X Rows Based On a Column's Value
In this article, we are going to learn how to use ORDER BY with TOP to return the top x rows based on a column's value. We will use another table to fetch the top value and use that value in another table. So first we create a database. Step 1: Create Database CREATE DATABASE GFG Step 2: Use this DB USE GFG Step 3: Create a table for storing the to
2 min read
Displaying the Employees in Decreasing Order of their Salaries in SQL Server
In SQL, we need to find out the department-wise information from the given table containing information about employees. One such data is the details of the employees sorted in decreasing order of their salaries. We shall use the ORDER BY clause to achieve this. This is illustrated below. For this article, we will be using the Microsoft SQL Server
2 min read
Displaying the Employees in Increasing Order of their Salaries in SQL Server
In SQL, we need to find out the department-wise information from the given table containing information about employees. One such data is the name of the department having the highest average salary of employees working in it. We shall use the ORDER BY clause to achieve this. This is illustrated below. For this article, we will be using the Microso
2 min read
Article Tags :