← Back to SQL, page 21

sql-0418 · Easy fresher

Predict SELECT EXISTS (SELECT NULL) and SELECT EXISTS (SELECT 1 WHERE 0).

The first returns 1 and the second 0. EXISTS only checks whether the subquery returns any row; the values in that row, even NULL, do not matter.

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_rowno_rowsscalar_null
101

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