In focus

How To Use ORDER BY Clause In T-SQL

In this article you will learn about ORDER BY clause. ORDER BY clause is use to display data in an ordered way.

Gagan Sharma Apr 12, 2016

ORDER BY clause is an optional element of a SELECT statement when you execute SQL queries to retrieve data from a database server.

In SQL, the purpose of using ORDER BY clause is to sort the data inthe order you want display it. It is optional to use it with a SELECT statement.

In cases where you want to execute SQL queries to retrieve data from a database server and to get a data set in a ordered way we use it.

SQL ORDER BY clause allows you to:
  • Sort data set in single column of values of multiple 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.
We can use ORDER BY on the outer query with ORDER BY in sub-queries. But we cannot use ORDER BY in views, inline functions, derived tables, and sub-queries, unless TOP function is specified.

Syntax:
  1. SELECT column_name, column_name  
  2. FROM table_name  
  3. ORDER BY column_name ASC | DESC, column_name ASC|DESC;  
Example: Let us suppose that we have a table as seen in the below given image.

table
Now, write a query to show ORDER By clause use.

Query: Select Top 2 * from Employees order by Employeeid Desc

Note: By default the ORDER By clause sort data in Ascending order.

Output:

table2
As you have learned about the ORDER BY clause it allows you to specify the order in which rows appears in the ResultSet. We can also use Alias with it.

Example: SELECT Employeeid, fname + ' ' + lname +'' As details FROM Employees ORDER BY Employeeid

Output:

table3

database order by sort

COMMENT USING