SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL Sorting Results

Back to: SQL Server Tutorial

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

SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
  • 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:

SELECT FirstName, LastName FROM Employees ORDER BY LastName;

2. Sorting by Multiple Columns

To sort by last name and then by first name, both in ascending order:

SELECT FirstName, LastName FROM Employees ORDER BY LastName, FirstName;

If you want to sort last names in ascending order and first names in descending order:

SELECT FirstName, LastName FROM Employees ORDER BY LastName ASC, FirstName DESC;

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:

SELECT FirstName, LastName, HireDate FROM Employees WHERE Department = 'Sales' ORDER BY HireDate DESC;

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:

SELECT FirstName, LastName FROM Employees ORDER BY LastName ASC NULLS LAST; -- Not supported in SQL Server, alternative approaches are needed

SQL Server does not support NULLS LAST directly in the ORDER BY clause, but you can work around it:

SELECT FirstName, LastName FROM Employees ORDER BY CASE WHEN LastName IS NULL THEN 1 ELSE 0 END, LastName;

Sorting with TOP

If you only need a subset of sorted results, use the TOP keyword:

SELECT TOP 10 FirstName, LastName FROM Employees ORDER BY HireDate DESC;

This returns the top 10 employees with the most recent hire dates.

Scroll to Top