ORDER BY in SQL Server

In the earlier articles we have seen how to use SELECT, WHERE, IN, DISTINCT etc commands.  These commands are used to retrieve the data from table(s).

By default when we run the select query , data will be retrieved in the same order in which it is inserted into table.

Example:

Here I have a students table with 5 records.

Below picture contains the result set when SELECT query is executed:





















In the above pictures Student Names are not in alphabetical order.

In order to fetch the data in alphabetical or sequential order we should be using ORDER BY clause in SQL Server.

ORDER BY clause in SQL Server is used to rearrange the data in the required order.

Syntax for the ORDER BY Statement is:

ORDER BY <Name of the columns> {ASC/DESC}

By default in ORDER BY clause data will be ordered or sorted by the the ascending order of the data.

That is explicitly ASC command will be considered in ORDER BY Clause if sort type is not mentioned.

Example: Here is the data from STUDENTS table sorted(ordered) based on their names.

Query: SELECT * FROM STUDENTS ORDER BY NAME

Result Set:

















in the above example student name are arranged alphabetically.

To arrange the data in the descending order of their names , use the following query:

Query: SELECT * FROM STUDENTS ORDER BY NAME DESC

Result Set:


















Using DESC keyword along with ORDER BY Clause data can be sorted in the descending order.

This entry was posted in . Bookmark the permalink.

Leave a reply