SQL POWER with fractional exponents
Covers what happens when the base is negative and the exponent is not a whole number: an error on SQL Server, PostgreSQL, MySQL and Oracle NUMBER, NULL on SQLite.
- Categoría
- Math
- Returns
float / numeric / NULL- In this category
- 27 of 82
Sintaxis
POWER(-8, 1.0/3.0)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | Raises 'An invalid floating point operation occurred' |
| PostgreSQL | Different name or syntax | Raises 'a negative number raised to a non-integer power yields a complex result' for double and numeric |
| MySQL | Different name or syntax | Raises 'DOUBLE value is out of range in pow(...)' |
| SQLite | Different name or syntax | Returns NULL |
| Oracle | Different name or syntax | NUMBER input raises ORA-01428; BINARY_DOUBLE input returns NaN |
Ejemplos
SQLite
SELECT POWER(-8, 1.0/3.0) AS r; -- NULL
PostgreSQL
SELECT POWER(-8::float8, 1.0/3.0) AS r; -- ERROR: ... yields a complex result
Any engine
SELECT SIGN(-8) * POWER(ABS(-8e0), 1e0/3) AS cube_root; -- -2
Conviene saberlo
- The failure is mathematical, not a bug: a negative base with a non-integer exponent has only complex roots, and C's pow() returns NaN for it, which each engine turns into an error or NULL.
- For odd roots the fix is sign-aware: SIGN(x) * POWER(ABS(x), 1e0/3) returns -2 for x = -8. On SQL Server, pass a float x, or POWER returns an INT and truncates the root.
- Negative bases with whole-number exponents are fine: POWER(-2, 3) is -8 on every engine.
Questions about POWER fractional
Why does POWER(-8, 1/3) return NULL or error?
A negative base with a non-integer exponent has no real result. SQLite returns NULL; SQL Server, PostgreSQL, MySQL and Oracle (NUMBER input) raise an error. Oracle BINARY_DOUBLE input returns NaN.
How do I take a cube root of a negative number?
Use the sign trick: SIGN(x) * POWER(ABS(x), 1e0/3), or CBRT() on PostgreSQL, which is defined for negative input. The 1e0 keeps the exponent a full-precision double on MySQL and SQL Server.
Does POWER(-2, 3) work?
Yes, the exponent is a whole number, so the sign is carried directly: POWER(-2, 3) is -8 on all engines. Only fractional exponents on negative bases fail.
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.