Learn SQL/Beginner/Filtering Data/SQL Operator Precedence

SQL Operator Precedence

AND binds tighter than OR — mixing them without parentheses can silently produce the wrong rows.

What & Why

When AND and OR appear in the same condition, Postgres evaluates AND first — exactly like multiplication binds tighter than addition in arithmetic. Without parentheses, the query might not mean what it looks like it means.

See How It Works

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT name FROM marketing.campaigns
WHERE channel = 'linkedin' OR channel = 'email' AND spend > 55000;
ACTUAL RESULT — AND is evaluated first
name
Finance Retargeting

SQL evaluates `channel = 'linkedin' OR (channel = 'email' AND spend > 55000)`, so Finance Retargeting survives. The mistaken grouping `(linkedin OR email) AND spend > 55000` would return no rows.

Now You Try

Practice this concept

Marketing wants active email campaigns plus every webinar campaign, regardless of status. Apply SQL logical precedence correctly.

Available schema
marketing

Prefix tables with marketing.table_name.

namechannelstatus
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario