The ORDERBY statement is used to sort the result set based on the specified column. The ORDERBY statement sorts the records in ascending order by default. If you want to sort the records in descending order, you can use the DESC keyword.
The order by statement is used to sort the result set based on the specified column. BY default, the order by statement sorts the records in ascending ORDER. If you want to sort the records in descending ORDER, you can use the DESC keyword.
The sorting can be ascending (ASC) or descending (DESC ). If the ascending or descending order is not specified, it is assumed as ASC.
The following query returns the results in ascending order of ProductID:
The Code is as follows: |
|
USE AdventureWorks2008R2; GO SELECT ProductID, ProductLine, ProductModelID FROM Production. Product Order by ProductID;
|
If the order by clause specifies multiple columns, the sorting is nested. The following statements first sort the rows in the Production. Product table in descending order of Product sub-categories, and then sort the rows in ascending order of ListPrice for each Product sub-category.
The Code is as follows: |
|
USE AdventureWorks2008R2; GO SELECT ProductID, ProductSubcategoryID, ListPrice FROM Production. Product Order by ProductSubcategoryID DESC, ListPrice; |
Problem
Why is the result set of the same query sometimes arranged in the desired order, sometimes not, or in the order of SQL2000, to SQL2005/2008?
In fact, as long as "order by" is not specified in the statement, SQLSERVER will not return in order. It is possible that an index has been created for a field in your table.
If you want to sort the result set by the indexed field, it is no problem if you do not specify "order by" because the table's storage order is based on the field
So you can not specify "order by", but if you have not created an index for the field you want to sort, or you have created an index in SQL2000
Index, but no index is created in SQL2005/2008. Therefore, you must explicitly specify the index with "order. If you do not specify the same query,
It is normal that the order of the result set is different from the previous one.