Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server equivalent to Oracle's NULLS FIRST?

So Oracle has NULLS FIRST, which I can use to have null values sorted at the top followed by my column value in descending order:

ORDER BY date_sent NULLS FIRST 

What is comparable in SQL Server? There are these alternatives, assuming the date values are NULL or in the past:

ORDER BY ISNULL(date_sent, GETDATE()) DESC ORDER BY (CASE WHEN t.setinactive IS NULL THEN 1 ELSE 2 END), t.setinactive DESC ORDER BY -CAST(date_sent as int) ASC 

Any others?

like image 377
OMG Ponies Avatar asked Sep 21 '09 20:09

OMG Ponies


People also ask

What is NVL equivalent in SQL Server?

ISNULL replaced the Oracle NVL function in the SQL server. When an expression in SQL server is NULL, the ISNULL function allows you to return an alternative value for the null.

How do I show the first NULL value in SQL?

If you sort a column with NULL values in ascending order, the NULLs will come first. Alternatively, if you add a DESC keyword to get a descending order, NULLs will appear last.

What can I use instead of NULL in SQL?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.

IS NULL in SQL Server?

SQL Server ISNULL() FunctionThe ISNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.


1 Answers

You can do some trick:

ORDER BY (CASE WHEN [Order] IS NULL THEN 0 ELSE 1 END), [Order]  
like image 166
Lukasz Lysik Avatar answered Oct 04 '22 05:10

Lukasz Lysik