How can I merge these 2 queries into 1 query? is it even possible? (Postgres 14)
select * from T
where T.guid = someguid
if the first query returns null, get the result of the second query:
select * from T
where T.default = 'true'
I read about 'exist' but it returns true/false and not the result itself, so couldn't figure out how to use it to solve my problem.
Thanks
Edit: the solution
I actually used both @Anton Grig and @a_horse_with_no_name answers, since my query has joins and lots of wheres, I created a query with a 'with' statement for a temp table, and a 'or' with a 'and not exists' query afterwards.
CodePudding user response:
You can use a common table expression
with t1 as (
select *
from T
where T.guid = someguid
)
select *
from t1
union all
select *
from T
where T.default = 'true'
and not exists (select * from t1);
The second part of the union will only be run, if the CTE didn't return anything. So it's either the first part or the second that returns something.
CodePudding user response:
as you mentioned, this can be done using exists as follows:
Select * From T
Where T.guid = someguid Or
(Not Exists (Select * From T Where T.guid = someguid) And T.default = 'true')
