SQL.What is SQL’s three-valued logic (TRUE, FALSE, UNKNOWN), and how do AND, OR, and NOT behave with UNKNOWN?

SQL uses **three-valued logic** because comparisons involving `NULL` generally produce **UNKNOWN**: SQL cannot determine whether the condition is true or false.

```sql
5 = 5       -- TRUE
5 = 3       -- FALSE
5 = NULL    -- UNKNOWN
NULL = NULL -- UNKNOWN
```

### AND, OR, and NOT with UNKNOWN

| Expression | Result |
|---|---|
| `TRUE AND UNKNOWN` | `UNKNOWN` |
| `FALSE AND UNKNOWN` | `FALSE` |
| `UNKNOWN AND UNKNOWN` | `UNKNOWN` |
| `TRUE OR UNKNOWN` | `TRUE` |
| `FALSE OR UNKNOWN` | `UNKNOWN` |
| `UNKNOWN OR UNKNOWN` | `UNKNOWN` |
| `NOT UNKNOWN` | `UNKNOWN` |

Remember: **FALSE determines an AND; TRUE determines an OR.** Otherwise, uncertainty remains.

### Practical pitfall

`WHERE` keeps only rows where the condition is **TRUE**. Both `FALSE` and `UNKNOWN` are excluded.

```sql
SELECT * FROM users WHERE age <> 18;
-- Also excludes users whose age is NULL.
```

To include users with an unknown age:

```sql
SELECT * FROM users
WHERE age <> 18 OR age IS NULL;
```

### Interview answer

“SQL uses TRUE, FALSE, and UNKNOWN to handle missing values. FALSE AND UNKNOWN is FALSE, TRUE OR UNKNOWN is TRUE, and NOT UNKNOWN remains UNKNOWN. WHERE returns only rows whose condition evaluates to TRUE.”
This entry was posted in Без рубрики. Bookmark the permalink.