PostgreSQL Operators

PostgreSQL operators let you compare values and combine conditions so you can filter and manipulate data precisely.

Comparison Operators

Comparison operators test the relationship between two values and always return a boolean result: true, false, or unknown (when NULL is involved). PostgreSQL supports the standard set: = for equality, <> or != for inequality, < and > for strictly less than or greater than, and <= and >= for inclusive bounds. These operators work on numbers, text, dates, and most other data types, comparing text using the current locale's collation rules.

  • = tests equality between two values
  • <> or != tests inequality (both are valid in PostgreSQL)
  • < and > test strict ordering
  • <= and >= test inclusive ordering
  • Comparisons involving NULL always evaluate to unknown, not true or false

Comparison operators in a WHERE clause

SELECT name, department, salary
FROM employees
WHERE salary > 50000;

Logical Operators

Logical operators combine multiple boolean expressions into a single condition. PostgreSQL implements the three standard logical operators: AND requires every condition to be true, OR requires at least one condition to be true, and NOT inverts a condition's truth value. These operators are most commonly used inside a WHERE clause to build precise multi-condition filters.

OperatorDescriptionExample
ANDTrue only when both sides are truesalary > 40000 AND department = 'Sales'
ORTrue when either side is truedepartment = 'Sales' OR department = 'Marketing'
NOTInverts a boolean expressionNOT (department = 'Sales')

Combining conditions with AND

SELECT name, department
FROM employees
WHERE department = 'Engineering' AND salary > 70000;
Note: Wrap grouped OR conditions in parentheses before combining them with AND. Without parentheses, PostgreSQL evaluates AND before OR, which can silently change the meaning of your query.

Grouping OR inside AND, with a NULL check

SELECT name, department
FROM employees
WHERE (department = 'Sales' OR department = 'Marketing')
  AND commission IS NOT NULL;

Operator Precedence and NULL

When PostgreSQL evaluates an expression without explicit parentheses, comparison operators run first, NOT runs next, AND runs before OR. Relying on this default order makes queries harder to read and easy to get wrong, so most teams add parentheses around every logical grouping regardless of precedence rules.

Note: Never compare a column to NULL using = or <>. Both expressions evaluate to unknown, so matching rows are silently excluded. Use IS NULL or IS NOT NULL instead.

Exercise: PostgreSQL Operators

Why does a condition like column = NULL never return true in PostgreSQL?