Order By in SQL

Rumman Ansari   Software Engineer   2023-03-25   5715 Share
☰ Table of Contents

Table of Content:


The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Syntax:


SELECT column1, column2, ..., columnN
FROM table_name
ORDER BY column1, column2, ... ASC|DESC

Prerequisite Codes

If you don't have table please create below table and practice it.

My database name is SQLExamples



USE SQLExamples

Create this below Employee table


DROP TABLE Employee
CREATE TABLE Employee(
EmpId INT,
EmpName VARCHAR(25),
EmpAddress VARCHAR(100),
EmpDept VARCHAR(25)
)

Insert data inside table


INSERT INTO Employee VALUES
(1, 'Rambo', 'Kolkata', 'IT'),
(2, 'Rohit', 'Kolkata', 'IT'),
(3, 'Rohon', 'Kolkata', 'ITIS'),
(4, 'Ronok', 'Kolkata', 'ITIS'),
(5, 'Rubin', 'Kolkata', 'ITIS'),
(6, 'Sorif', 'Kolkata', 'ADMIN'),
(7, 'Soriful', 'Kolkata', 'ADMIN'),
(8, 'Sofik', 'Kolkata', 'ADMIN')



SELECT * FROM Employee

Output:

The above code will produce the following result-

EmpId

EmpName

EmpAddress

EmpDept

1

Rambo

Kolkata

IT

2

Rohit

Kolkata

IT

3

Rohon

Kolkata

ITIS

4

Ronok

Kolkata

ITIS

5

Rubin

Kolkata

ITIS

6

Sorif

Kolkata

ADMIN

7

Soriful

Kolkata

ADMIN

8

Sofik

Kolkata

ADMIN

Example 1: ORDER BY

Code:


SELECT * FROM Employee
ORDER BY EmpDept

Output:

The above code will produce the following result-

EmpId

EmpName

EmpAddress

EmpDept

6

Sorif

Kolkata

ADMIN

7

Soriful

Kolkata

ADMIN

8

Sofik

Kolkata

ADMIN

1

Rambo

Kolkata

IT

2

Rohit

Kolkata

IT

3

Rohon

Kolkata

ITIS

4

Ronok

Kolkata

ITIS

5

Rubin

Kolkata

ITIS

Example 2: ORDER BY DESC

Code:


SELECT * FROM Employee
ORDER BY EmpDept DESC

Output:

The above code will produce the following result-

EmpId

EmpName

EmpAddress

EmpDept

3

Rohon

Kolkata

ITIS

4

Ronok

Kolkata

ITIS

5

Rubin

Kolkata

ITIS

1

Rambo

Kolkata

IT

2

Rohit

Kolkata

IT

6

Sorif

Kolkata

ADMIN

7

Soriful

Kolkata

ADMIN

8

Sofik

Kolkata

ADMIN

Example 3: ORDER BY Several Columns

Code:


SELECT * FROM Employee
ORDER BY EmpDept, EmpName

Example 4: ORDER BY Several Columns

Code:


SELECT * FROM Employee
ORDER BY EmpDept DESC, EmpName ASC