SQL ORDER BY

SQL ORDER BY clause with query example – Order By clause is used to sort the data either in ascending order or in descending order based on the specified column name or column number.

For example,

You may want to sort all books from a BOOKS table based on ISBN NO in ascending order. Or, you may want to sort employees details from Employee table in increasing order of Salary etc.

Points:

  • If you use SQL Select command without Order By to fetch records (e.g. Select * From BOOKS), then returned results will be in the same order as the records were inserted in the table, which is default sort order.
  • Order by used to sort the records in either ascending or descending order by using single or multiple columns.

SQL ORDER BY Syntax:

Order by syntax to sort the records either in ascending or descending order.

Syntax:

SELET column_1, column_2…..
FROM [WHERE [CONDITION]] ORDER BY  [COLUMN_NAME]  [ASC| DESC]

ASC: 
ASC- Ascending order is optional. It sorts the result set in ascending order based on the specified column.

DESC:
DESC- Descending order. It sorts the result set in descending order based on the specified column.

Sorting data in Ascending order example

SQL Query example to sort the data using order by clause in ascending order on column ISBN_NO in the table BOOKS

SQL Query

SELECT * FROM BOOKS ORDER BY ISBN_NO;
or
SELECT * FROM BOOKS ORDER BY ISBN_NO ASC;

ISBN_NO TITLE AUTHORFIRSTNAME AUTHORLASTNAME PRICE
181 The Castle Franz Kalka NULL
191 Animal Farm George Orwell NULL
205 Madhushala Girish Karnad NULL
209 Historica Herodotus Herodotus NULL

For the above 2 queries the result is same.  For first query it is not mentioned either asc or desc. By default, Order By clause can sort the the data in ascending order based on the ISBN_NO column.

Sorting data in Descending order example

SQL Query example to sort the data using order by clause in descending order on column ISBN_NO in the table BOOKS

SELECT * FROM BOOKS ORDER BY ISBN_NO DESC;

Output

ISBN_NO TITLE AUTHORFIRSTNAME AUTHORLASTNAME PRICE
209 Historica Herodotus Herodotus NULL
205 Madhushala Girish Karnad NULL
191 Animal Farm George Orwell NULL
181 The Castle Franz Kalka NULL

The above query sorts the result set in descending order based on the ISBN_NO column.