Null Safe Comparison Coalesce

Handle NULL values safely with COALESCE and IS NOT DISTINCT FROM for correct comparisons.

SqlData Integrity

Code

sqlsnippet
14 lines
-- NULL-safe equality (NULL = NULL returns NULL, not true)
SELECT * FROM users
WHERE email IS NOT DISTINCT FROM :filter_email;

-- Provide default with COALESCE
SELECT
  id,
  COALESCE(nickname, name) AS display_name,
  COALESCE(discount, 0) AS effective_discount
FROM users;

-- NULL-safe sorting (NULLs last)
SELECT * FROM tasks
ORDER BY priority DESC NULLS LAST, created_at ASC;

What the code does

The file runs SELECT statements, touching users and tasks.

Clause by clause, expect: a WHERE clause deciding which rows the statement applies to; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.

Applying it

Run the statement against the users table.

Statements that matter

SELECT * FROM users
WHERE email IS NOT DISTINCT FROM :filter_email;
SELECT
  id,
  COALESCE(nickname, name) AS display_name,
  COALESCE(discount, 0) AS effective_discount
FROM users;
SELECT * FROM tasks
ORDER BY priority DESC NULLS LAST, created_at ASC;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`users`, `tasks`.