SQL ORDER by

SQL ORDER BY Clause

SQL ORDER BY Clause

SQL ORDER BY Clause is used to to sort result-set in a particular order based on one or more columns.

  • ASC:   Ascending order, (default in some databases)
  • DESC: Descending order

Syntax of SQL ORDER BY Clause :

SELECT col1, col2, ...
FROM table_name 
WHERE conditions
ORDER BY expression [ASC/DESC];

Lets take a Employee Table with fields Emp_Id, FirstName, LastName, Salary, Gender, Phone.

Emp_Id FirstName LastName Salary Gender Phone
101 Sam Joseph 20000 M XXX0074321
201 Rohit Puri 45000 M xxxx768675
301 Jessica Alba 50000 F xxxx870977
401 Afroz Nawaz 75000 M xxxx836343
501 Aswathy Sam 60000 F xxxx886576
…. ……. ……. …… .. ………

Select First name, Salary  and Gender and sort the result set in descending Order

SELECT FirstName, Salary, Gender FROM Employee ORDER BY Salary DESC;  

FirstName Salary Gender
Afroz 75000 M
Aswathy 60000 F
Jessica 50000 F
Rohit 45000 M
Sam 20000 M

Use Order By Clause on Multiple Columns

In below example we will see how to use Order By Clause on Multiple columns. While using Order By on Multiple column, first it will sort according to 1st column name then suppose if value for 1st column name are same for some rows then it will sort according to second column and so on.

SELECT EmpId, FirstName, Salary FROM Employee ORDER BY Salary DESC, FirstName ASC;

EmpId FirstName Salary
102 Afroz 75000
104 Bivin 80000
402 Bivin 65000
302 Chris 70000
293 Derek 90000

Leave a Reply