Skip to content
Advertisement

PostgreSQL select record with multiple condition

I am trying to select the record but not getting the record I wanted. here is my sqlfiddle http://sqlfiddle.com/#!17/5296a/1

so when I selects the record using below query

select title from post where (id>3 and author_id=3) or id>3 limit 1

it gives me result with the title DDDDD. it should give me GGGGGGGG.

I wanted to check if there is any record with author_id=3 and greater than the post id=3 if not then just get the any post id greater than 3.

I am not sure what I am missing here.

Advertisement

Answer

I wanted to check if there is any record with author_id=3 and greater than the post id=3 if not then just get the any post id greater than 3.

From what you describe, you want:

select title
from post 
where id > 3
order by (author_id = 3) desc
limit 1;

Here is a db<>fiddle. This filters all the rows so there is just id > 3. The order by puts any rows with author_id = 3 first, so the limit would return that one.

Your version just returns an arbitrary row that matches the where condition — and that condition is equivalent to where id > 3. The where conditions don’t provide any sort of “preference”. They just specify whether or not a given row is in the result set.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement