James111
James111

Reputation: 15903

Postgres query multiple where clauses not working as expected

I've got the following notifications table:

| id (PK - INT) | user_id (UUID) | text (Text) | show_after (Date) default NULL | 

What I'm wanting todo is select all the notifs for the user_id, I also want to ensure that we DON'T show notifs where the show_after date is in future.

So if I want to show a notification after 5 days, I'd set show_after = NOW() + 5 days.

For some reason the query I've setup is behaving weirdly and will ALWAYS return the notifications where show_after === any date, even though some of the notifs have a show_after date set in the future.

Here is the query I tried:

select * from activities where user_id = '<uuid>' OR show_after = null AND 
show_after <= NOW();

I also tried switching around the OR/ANDs without success.

Upvotes: 1

Views: 4626

Answers (1)

Paul Maxwell
Paul Maxwell

Reputation: 35593

You need parentheses to control the logic

select * from activities 
where user_id = '<uuid>' 
and (
     show_after <= NOW()
   OR
     show_after IS NULL
    )
;

Additionally in SQL you must use IS NULL to determine if there is no value. Using the equal symbol will not work (NULL = NULL is always false).

Upvotes: 1

Related Questions