Skip to content
Advertisement

SQL WHERE condition when one does not return true, then try other

I have to query a table based on two fields such that if first field matches then don’t check the second but if first field does not match then check if second field matches for a value

something like:

SELECT * FROM table
WHERE cart_id=389 OR (cart_id IS NULL AND user_id=26)

But if first condition succeeds, it must not check for second condition

Example:

Suppose the following is my table

id | cart_id | user_id
1  | 389     | 26
2  | null    | 26
3  | 878     | 26
  • on querying for cart_id = 389 and user_id = 26, I should get back only record 1 and NOT 2
  • on querying for cart_id = 1 and user_id = 26, I should get back only records 2 and NOT 1 and 3

Advertisement

Answer

The only way I can think of, is to do this in two steps and check the result of the first step in the second:

with the_cart as (
   SELECT * 
   FROM the_table
   WHERE cart_id=389 
)
select *
from the_cart
union all
select *
from the_table
where cart_id IS NULL 
  AND user_id=26
  and not exists (select * from the_cart);

If the first query (using cart_id=389) returns something the second query from the union will not be run (or more precisely return no rows) due to the not exists() condition.

Online example

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