Explain Codes LogoExplain Codes Logo

In Clause with NULL or IS NULL

sql
null-handling
subqueries
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 7, 2025
TLDR

You can use a combination of IN and IS NULL to include values and NULLs.

SELECT * FROM table WHERE column IN (1, 2) OR column IS NULL;

This query returns rows where column is either 1, 2, OR NULL.

Swinging with subqueries in IN Clause

Executing more complex conditions? Don't panic. The IN clause accepts subquery results, your gateway to complex filtering:

SELECT * FROM table WHERE id_field IN (SELECT id FROM linked_table WHERE condition); -- Because who said that we can't have a query within a query?

However, this is a NULL-blind approach. To relieve NULL values from their invisibility cloak, toss in an OR with IS NULL:

SELECT * FROM table WHERE id_field IN (SELECT id FROM linked_table WHERE condition) OR id_field IS NULL; -- Null, where? Oh, there you are!

A piece, a slice, a coalesce

Ever dreamed of transforming NULL to a tangible value? The COALESCE function is all you need! It substitutes NULL with a default value, enabling matching with the IN clause:

SELECT * FROM table WHERE COALESCE(column, default_value) IN (1, 2, default_value); -- Donning our null values with cloaks of defaults. Fancy!

Handling the NOT IN beast

Beware, the NOT IN operator can get ferocious with NULL. If NULL sneaks into the list, the NOT IN condition returns FALSE. Ensure you send NULL away before using NOT IN:

SELECT * FROM table WHERE column NOT IN (SELECT id FROM linked_table WHERE column IS NOT NULL); -- We don't do Null in this NOT IN house!

Best practices in the realm of SQL

Level up your SQL game by:

  • Ditching the SELECT *: Itemise the much-needed columns.
  • Grouping conditions using parentheses: It's all about the correct precedence.
  • Polishing your SQL skills: Write queries that are clean, readable, and efficient.
  • Digging deeper: Articles, documentations for thorough understanding of NULL handling. You can't complain about what you don't understand, right?