PostgreSQL - Operators Precedence
PostgreSQL Operators Precedence
Operator precedence (order of operations) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given expression.
For example, multiplication has higher precedence than addition. Thus, the expression 1 + 2 × 3 is interpreted to have the value 1 + (2 × 3) = 7, and not (1 + 2) × 3 = 9. When exponent is used in the expression, it has precedence over both addition and multiplication. Thus 3 + 52 = 28 and 3 × 52 = 75.
Example:
Consider the following expressions:
--evaluates 5 * 2 first Result1 = 15 - 5 * 2; --above expression is equivalent to Result2 = 15 - (5 * 2); --forcing compiler to evaluate 15 - 5 first Result3 = (15 - 5) * 2;
Now, Consider a database table called Sample with the following records:
Data | Var1 | Var2 |
---|---|---|
Data1 | 10 | 1 |
Data2 | 15 | 2 |
Data3 | 20 | 3 |
Data4 | 25 | 4 |
Data5 | 30 | 5 |
Data6 | 35 | 6 |
The above discussed can be applied on the table Sample. Consider the example below:
SELECT *, Var1 - Var2 * 2 AS Result1, Var1 - (Var2 * 2) AS Result2, (Var1 - Var2) * 2 AS Result3 FROM Sample;
The above query will produce following result:
Data | Var1 | Var2 | Result1 | Result2 | Result3 |
---|---|---|---|---|---|
Data1 | 10 | 1 | 8 | 8 | 18 |
Data2 | 15 | 2 | 11 | 11 | 26 |
Data3 | 20 | 3 | 14 | 14 | 34 |
Data4 | 25 | 4 | 17 | 17 | 42 |
Data5 | 30 | 5 | 20 | 20 | 50 |
Data6 | 35 | 6 | 23 | 23 | 58 |
PostgreSQL Operators Precedence Table
The following table lists the precedence of PostgreSQL operators. Operators are listed top to bottom, in descending precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence.
Precedence | Operators | Associativity | Description |
---|---|---|---|
20 | :: | left | PostgreSQL-style typecast |
19 | [ ] | left | array element selection |
18 | . | left | table/column name separator |
17 | - | right | unary minus |
16 | ^ | left | exponentiation |
15 | *, /, % | left | multiplication, division, modulo |
14 | +, - | left | addition, subtraction |
13 | IS | test for TRUE, FALSE, UNKNOWN, NULL | |
12 | ISNULL | test for NULL | |
11 | NOTNULL | test for NOT NULL | |
10 | (any other) | left | all other native and user-defined operators |
9 | IN | set membership | |
8 | BETWEEN | containment | |
7 | OVERLAPS | time interval overlap | |
6 | LIKE, ILIKE | string pattern matching | |
5 | <, > | less than, greater than | |
4 | = | right | equality, assignment |
3 | NOT | right | logical negation |
2 | AND | left | logical conjunction |
1 | OR | left | logical disjunction |
❮ PostgreSQL - Operators