In the previous article, we went through How NOT IN works with NULL values. We also learned how we can overcome this restriction. In this article, we will look at alternative ways to handle NULL values with SQL functions.
So basically when we use != or NOT IN in query, it ignores the records with NULL values for fields.
User.where("state != ?", 'active')
SELECT * FROM users WHERE state != 'active'
OR
User.where("state NOT IN (?)", ['active'])
SELECT * FROM users WHERE state NOT IN ('active')
The above queries will consider records with state having a NOT NULL value, but state having a NULL value will not be considered. To consider state with the NULL value, we have to explicitly add the OR clause.
User.where("state != ? OR state IS NULL", 'active')
SELECT * FROM users WHERE state != 'active' OR state IS NULL
OR
User.where("state NOT IN (?) OR state IS NULL", ['active'])
SELECT * FROM users WHERE state NOT IN ('active') OR state IS NULL
Lets take a look at the alternatives for handling NULL values
-
With COALESCE function - MySQL/SQL Server/SQLite/PostgreSQL/Oracle
The
COALESCEfunction returns the first non-NULLexpression in the specified list. If all the arguments areNULL, then it will returnNULL.COALESCE(expression, replacement1...n)Here, considering
''(blank string) forNULLvalue while performing query to return records withNULLvalue.User.where("COALESCE(state, '') != 'active'") -
With IFNULL function in MySQL/SQLite
The MySQL
IFNULLfunction returns an alternative value if an expression isNULL.IFNULL(expression, replacement)User.where("IFNULL(state, '') != 'active'") -
With ISNULL function in SQL Server
The SQL Server
ISNULLfunction returns an alternative value if an expression isNULL.ISNULL(expression, replacement)User.where("ISNULL(state, '') != 'active'") -
With NVL function in Oracle
The Oracle
NVLfunction returns an alternative value if an expression isNULL.NVL(expression, replacement)User.where("NVL(state, '') != 'active'") -
With IS DISTINCT FROM statement in PostgreSQL
In
PostgreSQL, we can useIS DISTINCT FROMto work around the problems ofNULL, which treatNULLas a comparable value.attribute IS DISTINCT FROM valueUser.where("state IS DISTINCT FROM 'active'")

I hope you enjoyed this article and learned other ways of dealing with NULL values. Thank you for reading. ❤️
References