Article Information
This topic contains and tries to cover following subjects:
- Explanation of ORDER BY statement in SQL
- Syntax of ORDER BY statement in SQL
- Example of sorting the result set from a table in SQL
Articles contains and tries to provide answer to following questions and issues:
- How to sort the result set of a table in SQL
- How to specify a column to sort the table in SQL
Articles pre-requisites following information:
- General knowledge of basic query flow in SQL
- General knowledge of SQL Server Management Studio
Explanation of ORDER BY statement in SQL
In SQL, ORDER BY statement is used to sort to result set which is queried from a Table. In default behavior, SQL server returns rows in order of Primary Key as default behavior. In RDMB a relational data is assumed as unordered list, therefore the result set which is returned is not guranteed to be ordered. Idea behind is the specify the order of returned result set and tell to SQL server which column is going to be reference for sorting.
Syntax of ORDER BY statement in SQL
ORDER BY statement syntax is as follows:
SELECT - Column Name - FROM - Table Name -
ORDER BY - Column Name - ;
Example of ORDER BY statement in SQL
For demonstrating how ODER BY works in SQL, we will query sample database of Microsoft, adventureworks. Lets get all rows without ORDER BY statement first to see what is default sort behavior.
SELECT * FROM HumanResources.Department
Output:
As it is seen n above figure, SQL sorted the table according to the primary key column.
To sort the table according to the Name column, we place ORDER BY statement after the Table name. Following the statement, the column name is added. This tells SQL server to sort the table according to the provided column. Following figure indicates it:
We specified Name column for our example. Table is sorted according to the Name column, not according to primary key this time. MSDN link also indicates detailed use of ORDER BY.