login

SQL ORDER BY Clause

When you execute SQL queries to retrieve data from a database server, you get a data set in whatever orders it is. Therefore you need SQL ORDER BY clause to sort the data in order you want it to be. SQL ORDER BY clause allows you to:

  • Sort data set in single column of values of mutiple columns.
  • Sort any column in either ascending order (ASC) by default or descending order(DESC)
  • Refer to sort columns by name, by their position within the output column list of data set, or by using an alias

For example, if you want to get employee list by name, you can execute the query like this:

SELECT name,salary 
FROM employees  
ORDER BY name
name      salary 
--------  -------
anna      2800.00
foo       4700.00
jack      3000.00
mary      2500.00
newcomer  2000.00
Tom       2700.00

And the output is order by name in ascending order by default ( you can also add ASC keyword if you like to get the same result). To print in descending order you can add keyword DESC after the ORDER clause.

SELECT name,salary 
FROM employees  
ORDER BY name DESC
name      salary 
--------  -------
Tom       2700.00
newcomer  2000.00
mary      2500.00
jack      3000.00
foo       4700.00
anna      2800.00

Now think about a situation when you want who is in your company has highest salary you can order employee list in both salary in descending order and name in ascending order.

SELECT name,salary 
FROM employees  
ORDER BY salary DESC, name ASC
name      salary 
--------  -------
foo       4700.00
jack      3000.00
anna      2800.00
Tom       2700.00
mary      2500.00
newcomer  2000.00
Read On