Reputation: 5691
I need a sql query to apply a condition only if the value is present. For eg. consider the table person
sl Name city state
--------------------------------------
1 xxxxxxxx chennai TN
2 yyyyyyyy coimbatore TN
3 zzzzzzzz cochin KL
consider the following query
select * from person where state = "AD" and city = "visag"
will returns 0 rows
i want a query to apply 'state = "AD" and city = "visag"' only if state = "AD" is present.
is there any way to do this in a single select query?
Upvotes: 0
Views: 47
Reputation: 94914
Whether 'AD' exists or not is just another condition:
select *
from person
where (state = 'AD' and city = 'visag')
or not exists
(
select *
from person
where state = 'AD'
);
Upvotes: 1
Reputation: 204756
select * from person
where state = "AD" and city = "visag"
or (select count(*) from person where state = "AD") = 0
Upvotes: 0