# nullable-write

Default severity: **warn**

## What it does

Reports a value that can be NULL, such as a nullable column, a scalar subquery or a `LEFT JOIN` column, that a write puts in a column the schema declares `NOT NULL`. It checks the same statements as [`null-write`](<https://sqlty.kuncar.dev/reference/rules/null-write/index.md>), which reports a literal `NULL`. A condition that rules NULL out is taken into account: a `WHERE`, the `AND` of a `MERGE` clause and the earlier clauses of its kind, and `ON CONFLICT DO UPDATE SET col = EXCLUDED.col` follows the value the INSERT proposed. A parameter's nullability, also through a VALUES list or `unnest` it fills, is not known here: `sqlty check` compares the Python type of the argument with the column (see [`params-type-mismatch`](<https://sqlty.kuncar.dev/reference/rules/params-type-mismatch/index.md>)).

## Why is this bad?

PostgreSQL rejects the statement with `NotNullViolation` when the value is NULL, which the code may not have met yet: a subquery that finds no row, a row without a nickname.

## Example

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

`schema.sql`:

```sql
CREATE TABLE person (id INT PRIMARY KEY, first_name TEXT NOT NULL, nickname TEXT);
CREATE TABLE pet (id INT PRIMARY KEY, name TEXT NOT NULL);
```

```python
# error: [nullable-write] "`person.first_name` is NOT NULL, but `nickname` can be NULL"
nick = "--sql\nUPDATE person SET first_name = nickname WHERE id = %s"
# error: [nullable-write] "`person.first_name` is NOT NULL, but `(SELECT name FROM pet LIMIT 1)` can be NULL"
pet = "--sql\nUPDATE person SET first_name = (SELECT name FROM pet LIMIT 1) WHERE id = %s"
# error:
known = "--sql\nUPDATE person SET first_name = nickname WHERE nickname IS NOT NULL"
```

Use `COALESCE` with a fallback, or a `WHERE` that keeps the NULL out.
