Trying to understand why IS NOT NULL is necessary at end of query and case statement in SQL


I’m working on a query in DataCamp SQL and I don’t understand the ending to this query:

FROM matches_italy
-- Exclude games not won by Bologna
    CASE WHEN hometeam_id = 9857 AND home_goal > away_goal THEN 'Bologna Win'
        WHEN awayteam_id = 9857 AND away_goal > home_goal THEN 'Bologna Win' 
        *END IS NOT NULL;*

It’s the very last line I don’t get.

MY thoughts would be to not have anything written after END, because obviously you wouldn’t want to select any NULLS, because you are specfiying the only data you will accept, right there in the WHERE clause, right? So I would think it would end just as:


Otherwise, if anything is to be put there, wouldn’t it be something like:



But I still think in my mind you shouldn’t have to respecify that you don’t want something other than what is already there in the case statement.

Many thanks!!

>Solution :

Because this is in the WHERE statement, there needs to be a comparison happening. The comparisons between CASE and END are simply deciding what value to return, but that value must be compared to something.

So this syntax is saying, WHERE {{ what case statement returns }} IS NOT NULL

The reason this is confusing, is because you could essentially eliminate the CASE portion and write the WHERE clause yourself, which would be easier to understand, imho. Contributing to the confusion is the CASE portion not explicitly returning NULL for any condition, because it is relying on the fact that there is no ELSE in order to return a NULL. Thats a lot of mental energy to figure out what that WHERE clause is doing.

WHERE NOT (hometeam_id = 9857 AND home_goal > away_goal)
AND NOT (awayteam_id = 9857 AND away_goal > home_goal)

Leave a Reply Cancel reply