SQL NULL in arithmetic
Explains three-valued logic in math expressions: unknown propagates through + - * / and functions, with the COALESCE and NULLIF patterns that tame it.
- カテゴリ
- Math
- Returns
NULL / numeric- In this category
- 79 of 82
構文
5 + NULL
COALESCE(x, 0) + 5
x / NULLIF(y, 0)
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | Supported under this name. |
| PostgreSQL | はい | Supported under this name. |
| MySQL | はい | Supported under this name. |
| SQLite | はい | Supported under this name. |
| Oracle | はい | Supported under this name. |
例
Any engine
SELECT 5 + NULL AS unknown; -- NULL
Any engine
SELECT COALESCE(bonus, 0) + salary AS total_comp FROM employees;
Any engine
SELECT x / NULLIF(y, 0) AS safe_div FROM t; -- NULL instead of an error
知っておくと便利なこと
- NULL is contagious by design: 5 + NULL, NULL * 10 and LN(NULL) are all NULL, because an unknown operand makes the result unknown.
- COALESCE supplies the default, but think first: COALESCE(bonus, 0) changes an unknown bonus into no bonus; only do that when zero is truly the meaning.
- Aggregates are the exception: SUM, AVG, MIN and MAX skip NULL inputs rather than returning NULL, though SUM over zero rows is still NULL.
Questions about NULL math
What does 5 + NULL return in SQL?
NULL, on every engine. SQL's three-valued logic says an unknown operand makes the whole expression unknown. Wrap operands in COALESCE(x, 0) only when zero genuinely matches the meaning.
Why did my AVG ignore NULLs but my + did not?
Aggregates skip NULL inputs before computing; scalar arithmetic propagates them. AVG(bonus) divides by the non-null count, while bonus + salary is NULL whenever either side is NULL.
How do I turn division-by-zero into NULL instead of an error?
NULLIF in the divisor: x / NULLIF(y, 0). The zero becomes NULL, the division returns NULL, and the query survives: the NULL-propagation rule working for you.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.