SQL - Query Flow - ORDER BY statement - Sorting values in specified column from highest value to lowest value.
Nisan 4, 2011 by Microsoft
|
|
Article Information
This topic contains and tries to cover following subjects:
- Explanation of sorting results in decreasing order with ORDER BY clause in SQL
- Syntax of sorting results in decreasing order with ORDER BY clause in SQL
- Example of sorting results in ascending order in SQL
Articles contains and tries to provide answer to following questions and issues:
- How to sort values from highest value to lowest value?
- How to sort values in specified column with providing decreasing expression
Articles pre-requisites following information:
- Basic query flow in SQL
- SQL Server Management Studio 2008
- ORDER BY clause
Explanation of sorting results in decreasing order with ORDER BY clause 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 guaranteed 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.
By default, result set is in ascending order. Values in the specified column are sorted from lowest to high. When you query SQL to fill a dataset for example, programmer may require to get the query result in decreasing order. In C# side, this can also be achieved programmatically, but SQL provides easier approach.
Syntax of ORDER BY statement in SQL
To sort in decreasing order we add "DESC" keyword to query after column name which is specified as sort reference.
SELECT - Column Name - FROM - Table Name -
ORDER BY - Column Name - DESC;
Example of ORDER BY statement in SQL
For demonstrating how descending order in SQL works, we will query sample database of Microsoft, adventureworks. Lets get all rows without ORDER BY statement first to see what is default sort behavior. Ascending (from lowest to high) is expected as default bahaviour.
SELECT * FROM HumanResources.Department
Output:
As it is seen n above figure, SQL sorted the table according to the primary key column in ascending oder.
To sort the table according to the Name column, and in descending order we place ORDER BY statement after the Table name, and "DESC" keyword after column name.
Adding DESC keyword means, we tell SQL to get result in decreasing order, opposite of default bahaviour.
We specified Name column, and sort type. Table is sorted according to the Name column, not according to primary key this time, and in decreasing order.
Data Layers
Area: | programming \ languages \ tsql \ \ \ |
Ref: | http://msdn.microsoft.com/en-us/library/ms188385.aspx |
Loc: | articles |
Tags: | tsql |
|