SQL operator precedence
The order in which SQL evaluates mixed math operators: unary sign first, then multiply/divide/modulo, then add/subtract, and parentheses beat everything.
- Categoría
- Math
- Returns
n/a- In this category
- 53 of 82
Sintaxis
a + b * c
(a + b) * c
-2 ^ 2 -- PostgreSQL: 4
Each block is a separate form. The support table and the examples show which engine takes which.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | ^ (power) sits below unary minus and above * /, and is left-associative: 2 ^ 3 ^ 2 is 64 |
| MySQL | Sí | Supported under this name. |
| SQLite | Sí | Plain four-operator precedence plus %; no power operator at all |
| Oracle | Sí | No % and no power operator in SQL; MOD and POWER are functions, so only + - * / and unary sign apply |
Ejemplos
Any engine
SELECT 2 + 3 * 4 AS fourteen, (2 + 3) * 4 AS twenty; -- 14, 20
PostgreSQL
SELECT -2 ^ 2 AS four, -(2 ^ 2) AS minus_four, 2 ^ 3 ^ 2 AS sixty_four; -- 4, -4, 64
SQL Server
SELECT 100 / 10 % 3 AS left_to_right; -- 1
Conviene saberlo
- * / % always beat + -: SELECT 2 + 3 * 4 returns 14, not 20, on every engine.
- PostgreSQL's ^ breaks schoolbook order: unary minus binds first, so -2 ^ 2 is 4 (Python gives -4), and 2 ^ 3 ^ 2 is (2 ^ 3) ^ 2 = 64 rather than 512.
- Division and modulo share one level and evaluate left to right: 100 / 10 % 3 is (100 / 10) % 3 = 1.
Questions about precedence
What is the order of operations in SQL?
Unary minus/plus, then PostgreSQL's ^ where it applies, then * / %, then + -, all left-to-right within a level. Parentheses override everything and cost nothing.
Does ^ bind tighter than unary minus?
No, not on PostgreSQL: -2 ^ 2 is 4 because the minus applies to 2 first. Write -(2 ^ 2) when you mean -4. On SQL Server and MySQL, ^ is XOR and sits with the bitwise operators.
Is it safe to rely on precedence?
For a * b + c, yes: every reader knows it. For expressions mixing power, negation and division across engines, add parentheses: they document intent and prevent cross-dialect surprises.
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.