Learn SQL/Intermediate/NULL Handling/SQL Three-Valued Logic

SQL Three-Valued Logic

SQL doesn't have just TRUE and FALSE — every condition can also evaluate to UNKNOWN, which is what NULL comparisons actually produce.

What & Why

Ordinary logic has two values: TRUE and FALSE. SQL has three: TRUE, FALSE, and UNKNOWN — the result of any comparison involving NULL. A WHERE clause only keeps rows where the condition evaluates to TRUE; both FALSE and UNKNOWN get filtered out identically, which is exactly why NULL-involving comparisons so often silently exclude rows rather than erroring.

See How It Works

BUSINESS QUESTION

Product wants feedback ratings labeled positive, other, or unknown when no rating was submitted.

iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-04-08 17:30:00+00
EXAMPLE QUERY
SELECT
  id AS feedback_id,
  rating,
  CASE
    WHEN rating >= 4 THEN 'positive'
    WHEN rating < 4 THEN 'other'
    ELSE 'unknown'
  END AS rating_state
FROM product.feedback
ORDER BY feedback_id;
RESULT — exact output from the displayed Queryflo rows
feedback_idratingrating_state
15positive
24positive
34positive
43other

No displayed rating is NULL, so the unknown branch does not appear in this result.

Intermediate business practice

Sign up free to try it on a real business scenario