📜  sql server order by nulls last - SQL (1)

📅  最后修改于: 2023-12-03 14:47:35.573000             🧑  作者: Mango

SQL Server Order By Nulls Last

When ordering data in SQL Server, it's common to use the ORDER BY clause to sort the records by a specific column in ascending or descending order. However, when dealing with null values in the sorted column, it can become tricky to get the desired result.

The ORDER BY NULLS LAST clause is a solution to this problem. It allows you to sort the data, with null values appearing at the bottom of the sorted list.

Syntax

The syntax for using ORDER BY NULLS LAST in SQL Server is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC | DESC] NULLS LAST;

In the ORDER BY clause, you specify the column by which you want to sort the records. The NULLS LAST option ensures that the null values appear at the end of the sorted list, after all the non-null values. You can also use NULLS FIRST if you want null values to appear at the top of the list.

Example

Here's an example demonstrating the use of ORDER BY NULLS LAST in SQL Server:

SELECT name, age
FROM users
ORDER BY age DESC NULLS LAST;

In this example, we have a "users" table with columns "name" and "age". We want to sort the records by the "age" column in descending order and have the null values appear at the bottom of the list.

Conclusion

ORDER BY NULLS LAST is a useful clause in SQL Server that allows you to order data while handling null values in a desired way. Whether you want null values to appear at the top or bottom of the list, you can achieve it with this clause.