Skip to content
Advertisement

How to use IS NOT NULL on a case when?

I have the below SQL query in SSMS where I want to exclude NULL rows that show up in the ‘intercompany budget’ columns.

I’ve tried to search for answers and putting a WHERE clause for 'Intercompany Budget' IS NOT NULL, like in the query below, but NULL rows still show up.

Any suggestions? Thanks!

Advertisement

Answer

'Intercompany Budget' IS NOT NULL can never be true, 'Intercompany Budget' is a literal string and thus doesn’t have the value NULL. This is actually one reason why using literal strings for aliases is a bad habit, as it causes misunderstandings like this. 'Intercompany Budget' doesn’t refer to the column with the alias defined using AS 'Intercompany Budget'; it’s literally a literal string. It’s only in aliasing that the syntax is (unfortunately) accepted.

If you must use aliases that need to be delimit identified, then use the dialect’s delimit identifier, brackets ([]) in T-SQL, or the ANSI delimit identifier, double quotes ("). Ideally, however, don’t use aliases/names that require delimit identification at all. I tend to use PascalCase (as shown below).

As for filtering out the rows, one method would be to use a CTE:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement