# nullable-not-in

Default severity: **warn**

## What it does

Reports `x NOT IN (SELECT y ...)` when `y` can be NULL, and `x NOT IN (...)` over a list that holds a `NULL` literal.

```toml
[tool.sqlty]
schema = "schema.sql"
dialect = "postgres"
```

`schema.sql`:

```sql
CREATE TABLE users (id INT PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (id INT PRIMARY KEY, user_id INT REFERENCES users (id));
```

```python
from sqlty import SQL

# error: [nullable-not-in] "`NOT IN` over `user_id`, which can be NULL, is never true when it holds a NULL: use `NOT EXISTS`"
q = SQL[tuple[int]]("--sql\nSELECT id FROM users WHERE id NOT IN (SELECT user_id FROM orders)")
```

A column that can't be NULL is not reported: a `NOT NULL` column, one the subquery filters with `IS NOT NULL`, joins or wraps in `COALESCE`:

```python
from sqlty import SQL

# error:
q = SQL[tuple[int]]("--sql\nSELECT id FROM users WHERE id NOT IN (SELECT user_id FROM orders WHERE user_id IS NOT NULL)")
r = SQL[tuple[int]]("--sql\nSELECT id FROM users WHERE id NOT IN (SELECT id FROM orders)")
```

## Why is this bad?

`2 NOT IN (1, NULL)` is NULL, not true, so once the subquery returns one NULL the query returns no rows. With users 1 and 2 and an order of user 1 next to one with no user, PostgreSQL returns no users, though user 2 has no orders.

## How to fix

Use `NOT EXISTS`, which ignores NULLs. `sqlty check --fix` writes it for a qualified `x NOT IN (SELECT y FROM ...)` the subquery can't capture:

```sql
SELECT id FROM users u WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id)
```

Or filter the NULLs out of the subquery with `WHERE user_id IS NOT NULL`.

## Configuration

A warning by default: the query is valid SQL. Turn it into an error or off:

```toml
[tool.sqlty.rules]
nullable-not-in = "error"
```

Needs a schema to know whether a column can be NULL; a subquery with a parameter is not judged.
