RefLib

Reference library for AI

Back

postgresql_16:3.1.1.6 Operator Precedence

PostgreSQL 16 > The SQL Language > SQL Syntax > Lexical Structure > Operator Precedence

(see sql-precedence-table) shows the precedence and associativity of the operators in PostgreSQL. Most operators have the same precedence and are left-associative. The precedence and associativity of the operators is hard-wired into the parser. Add parentheses if you want an expression with multiple operators to be parsed in some other way than what the precedence rules imply.

| Operator/Element | Associativity | Description | | --- | --- | --- | | . | left | table/column name separator | | :: | left | PostgreSQL-style typecast | | [ ] | left | array element selection | | + - | right | unary plus, unary minus | | COLLATE | left | collation selection | | AT | left | AT TIME ZONE | | ^ | left | exponentiation | | * / % | left | multiplication, division, modulo | | + - | left | addition, subtraction | | (any other operator) | left | all other native and user-defined operators | | BETWEEN IN LIKE ILIKE SIMILAR | | range containment, set membership, string matching | | < > = <= >= <> | | comparison operators | | IS ISNULL NOTNULL | | IS TRUE, IS FALSE, IS NULL, IS DISTINCT FROM, etc. | | NOT | right | logical negation | | AND | left | logical conjunction | | OR | left | logical disjunction |

Note that the operator precedence rules also apply to user-defined operators that have the same names as the built-in operators mentioned above. For example, if you define a “+” operator for some custom data type it will have the same precedence as the built-in “+” operator, no matter what yours does.

When a schema-qualified operator name is used in the OPERATOR syntax, as for example in: SELECT 3 OPERATOR(pg_catalog.+) 4; the OPERATOR construct is taken to have the default precedence shown in (see sql-precedence-table) for “any other operator”. This is true no matter which specific operator appears inside OPERATOR().

Note

PostgreSQL versions before 9.5 used slightly different operator precedence rules. In particular, <= >= and <> used to be treated as generic operators; IS tests used to have higher priority; and NOT BETWEEN and related constructs acted inconsistently, being taken in some cases as having the precedence of NOT rather than BETWEEN. These rules were changed for better compliance with the SQL standard and to reduce confusion from inconsistent treatment of logically equivalent constructs. In most cases, these changes will result in no behavioral change, or perhaps in “no such operator” failures which can be resolved by adding parentheses. However there are corner cases in which a query might change behavior without any parsing error being reported.

Back