SQL

Lesson 03

Filtering and NULL handling

Use SQL NULL operators and explicit boolean logic so filters match real data.

Good Code

review-filters.sql
SELECT id, title, approved_at
FROM code_reviews
WHERE deleted_at IS NULL
  AND (
    approved_at IS NULL
    OR approved_at >= CURRENT_DATE - INTERVAL '30 days'
  )
ORDER BY submitted_at DESC;

Bad Code

review-filters.sql
SELECT id, title, approved_at
FROM code_reviews
WHERE deleted_at = NULL
  AND approved_at != NULL
   OR approved_at >= CURRENT_DATE - INTERVAL '30 days'
ORDER BY submitted_at DESC;

Review Notes

What to review

Good Code

The good version uses IS NULL and groups the OR condition so deleted rows cannot leak into the result.

Bad Code

The bad version compares to NULL with equality operators and relies on ambiguous operator precedence. It can return the wrong rows or no rows at all.

Takeaways

  • NULL is not equal to anything, so review nullable filters with extra care.