SQLConfiguration SQLConfiguration

Basic Queries  «Prev 

Using the ORDER BY clause

ORDER BY Clause (Transact-SQL)

Sorts data returned by a query in SQL Server. Use this clause to:
  1. Order the result set of a query by the specified column list and, optionally, limit the rows returned to a specified range. The order in which rows are returned in a result set are not guaranteed unless an ORDER BY clause is specified.
  2. Determine the order in which ranking function values are applied to the result set.

ORDER BY order_by_expression
    [ COLLATE collation_name ] 
    [ ASC | DESC ] 
    [ ,...n ] 
[ <offset_fetch> ]

<offset_fetch> ::=
  OFFSET { integer_constant | 
	offset_row_count_expression } { ROW | ROWS }
   FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY
This SELECT statement returns the table in the same order as the rows that appear in the table.

The results look like this in the Web browser. Notice the records appear in no specific order other than how they appear in the table.

SELECT * FROM BookTable 
This statement uses the ORDER BY clause to sort the rows by the author's name

Now the table is displayed in ascending order by the author's name

ORDER By Author, Title
The ORDER BY clause will also sort multiple columns. To do this, simply separate the column names by a comma. The ORDER BY clause in this statement specifies that the results be sorted first by Author, then by Title.

Here are the results displayed in the browser.

In some cases you might want to sort the output in descending order. To do this, add the expression DESC just after the column name. Even though ascending order is the default, you can specify ascending order in the ORDER BY clause by adding ASC after the column name. Here is the unsorted BookTable.

Title DESC
The ORDER BY clause instructs the statement to sort the Author colum in ascending order and the Title column in descending order. The use of ASC is optional because ascending is the default sort order.

Here is the table after the sort