iskandarblue
iskandarblue

Reputation: 7526

Combining AND OR statements in Postgres

I would like to write a query that selects records by a number of different conditions and that uses operators AND and OR.

If I write the following query, for example, how do I keep the first two conditions (network_id = 1 and payment_plan_id = 77) without rewriting them after the OR statement?

select * from transactions where network_id = 1 and payment_plan_id = 
77 and payment_type = 'Subscription' OR payment_type = 'Renewal'

Upvotes: 0

Views: 1764

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93704

Use IN to avoid the parenthesis confusion

select * from transactions 
where network_id = 1 
and payment_plan_id = 77 
and payment_type IN ('Subscription' , 'Renewal')

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269693

Use parentheses:

select *
from transactions
where network_id = 1 and payment_plan_id = 77 and 
      (payment_type = 'Subscription' OR payment_type = 'Renewal')

Or, better yet, use in:

select *
from transactions
where network_id = 1 and payment_plan_id = 77 and 
      payment_type in ('Subscription', 'Renewal')

Upvotes: 4

Related Questions