SQL exponentiation operator
The caret raises to a power on PostgreSQL only. On SQL Server and MySQL ^ is bitwise XOR, SQLite has no ^, and Oracle SQL has no power operator at all.
- 类别
- Math
- Returns
double / numeric- In this category
- 26 of 82
语法
base ^ exponent -- PostgreSQL
base ** exponent -- Oracle PL/SQL only
POWER(base, exponent) -- everywhere
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | ^ is the bitwise XOR operator, not power |
| PostgreSQL | 是 | ^ is exponentiation for both double precision and numeric; 2.0 ^ 2 stays numeric |
| MySQL | Not built in | ^ is the bitwise XOR operator, not power |
| SQLite | Not built in | There is no ^ operator at all in SQLite |
| Oracle | Not built in | No operator in SQL: SELECT 2 ** 10 FROM dual raises ORA-00936. ** exists only in PL/SQL; use POWER in queries |
示例
PostgreSQL
SELECT 2 ^ 10 AS power_result; -- 1024
PostgreSQL
SELECT -2 ^ 2 AS neg_first, 2 ^ 3 ^ 2 AS left_assoc; -- 4, 64
SQL Server
SELECT 2 ^ 3 AS xor_result; -- 1, not 8
Any engine
SELECT POWER(2, 10) AS portable_power;
值得了解
- Migrating T-SQL or MySQL code to PostgreSQL can silently turn 2 ^ 3 from an XOR (1) into a power (8); both are legal, both return a number.
- PostgreSQL ^ breaks math convention twice: unary minus binds tighter, so -2 ^ 2 is 4, and ^ associates left to right, so 2 ^ 3 ^ 2 is 64, not 512.
- Oracle's ** is a PL/SQL operator. Inside a SQL statement it is a syntax error, so code copied from a PL/SQL block into a query must switch to POWER.
Questions about ^
Does ^ mean power in SQL?
Only on PostgreSQL. In SQL Server and MySQL it is bitwise XOR, and SQLite has no ^ at all. Use POWER() when the query must run on more than one engine.
What is the Oracle exponentiation operator?
In SQL there is none: SELECT 2 ** 10 FROM dual fails with ORA-00936. ** works in PL/SQL expressions only. Use POWER(2, 10) in queries.
Why is -2 ^ 2 equal to 4 in PostgreSQL?
Unary minus binds tighter than ^ in PostgreSQL, so it parses as (-2) ^ 2. Write -(2 ^ 2) when you mean -4. ^ is also left-associative: 2 ^ 3 ^ 2 is (2 ^ 3) ^ 2 = 64.
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: PostgreSQL.
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.