Sorting results in SQL Server is done using the ORDER BY
clause. This clause allows you to specify the columns by which you want to sort your result set and the direction of sorting (ascending or descending). Here’s a quick guide on how to use ORDER BY
:
Basic Syntax
column1, column2, ...
: The columns you want to retrieve.table_name
: The name of the table from which you are retrieving the data.ORDER BY column1
: The column by which to sort the results.ASC
: Sorts in ascending order (this is the default if not specified).DESC
: Sorts in descending order.
Examples
1. Simple Sorting
To retrieve a list of employees sorted by their last names in ascending order:
2. Sorting by Multiple Columns
To sort by last name and then by first name, both in ascending order:
If you want to sort last names in ascending order and first names in descending order:
3. Sorting with Expressions
You can also sort by an expression. For example, if you want to sort employees by their hire date, but only show those with a specific department:
4. Sorting with NULL Values
By default, NULL values are sorted last when using ASC
and first when using DESC
. If you want to explicitly specify the sorting of NULLs:
SQL Server does not support NULLS LAST
directly in the ORDER BY
clause, but you can work around it:
Sorting with TOP
If you only need a subset of sorted results, use the TOP
keyword:
This returns the top 10 employees with the most recent hire dates.