SQL log of zero and negatives
Covers non-positive input to LN and LOG: which engines soften it to NULL, which fail the statement, and the CASE/NULLIF patterns that keep queries alive.
- Categoria
- Math
- Returns
float / NULL / error- In this category
- 74 of 82
Sintaxe
LN(0)
LN(-1)
CASE WHEN x > 0 THEN LN(x) END
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | LOG(0) raises 'An invalid floating point operation occurred'; LOG of a negative also fails |
| PostgreSQL | Sim | ERROR: cannot take logarithm of zero (and of a negative number) |
| MySQL | Different name or syntax | Returns NULL with a warning for zero and negative input |
| SQLite | Different name or syntax | Returns NULL |
| Oracle | Sim | ORA-01428: Argument 0 is out of range (likewise for negatives) |
Exemplos
MySQL
SELECT LN(0) AS ln_zero; -- NULL
PostgreSQL
SELECT LN(0) AS boom; -- ERROR: cannot take logarithm of zero
PostgreSQL
SELECT CASE WHEN x > 0 THEN LN(x) END AS safe_log FROM t;
SQL Server
SELECT CASE WHEN x > 0 THEN LOG(x) END AS safe_log FROM t; -- SQL Server spells LN as LOG
Bom saber
- The domain of every real logarithm is (0, infinity). The same rows that return NULL on MySQL abort the whole statement on PostgreSQL, so a query can pass tests on one engine and fail in production on another.
- Guard with CASE WHEN x > 0 THEN LN(x) END (LOG(x) on SQL Server) for a NULL result on every engine, or filter WHERE x > 0 to drop the rows.
- For the same soft-NULL treatment with a fallback, wrap: COALESCE(CASE WHEN x > 0 THEN LN(x) END, 0).
Questions about LOG(0)
What does LN(0) return?
NULL on MySQL and SQLite; an error on PostgreSQL, Oracle and SQL Server. There is no real logarithm of zero, so the engines either fail the statement or soften it to NULL.
How do I log-guard a column with zeros?
CASE WHEN x > 0 THEN LN(x) END (LOG(x) on SQL Server) yields NULL for non-positive values on every engine; a WHERE x > 0 filter drops the rows instead. Pick based on whether NULLs or missing rows fit the report.
Why does the same query work on MySQL but fail on PostgreSQL?
MySQL's NULL-on-domain-error philosophy versus PostgreSQL's error philosophy: the same split shows up in ASIN, ACOS and division by zero. Portable SQL guards the domain explicitly.
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.