Full answer
sql
SELECT EXISTS (SELECT NULL) AS has_null_row, EXISTS (SELECT 1 WHERE 0) AS no_rows, (SELECT NULL) IS NULL AS scalar_null;| has_null_row | no_rows | scalar_null |
|---|---|---|
| 1 | 0 | 1 |
SELECT NULL produces one row containing NULL, which is still a row, so EXISTS is true. SELECT 1 WHERE 0 produces no rows, so EXISTS is false. The third column shows the contrast with a scalar subquery, whose value is NULL either when the row holds NULL or when there is no row, which is why a scalar subquery cannot tell the two cases apart. This is also why the select list inside EXISTS is conventionally SELECT 1: it is never read.
sql
SELECT EXISTS (SELECT NULL) AS has_null_row, EXISTS (SELECT 1 WHERE 0) AS no_rows, (SELECT NULL) IS NULL AS scalar_null;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- EXISTS tests for rows, not values
- A row of NULLs still counts
- Scalar subqueries conflate NULL and no row
Common mistakes
- Thinking EXISTS (SELECT NULL) is false
Follow-ups
- Why do people write SELECT 1 inside EXISTS?
- How does NOT EXISTS behave with NULL columns?
Tips
- Count rows, ignore values