I have a situation like this:
with
my_data as (
select A.a1,B.b1,B.b2
from some_table A
left join lateral (
select b1, b2 from X where X.id = A.id limit 1
) B ON TRUE
)
select * from my_data where b1 is not null
union all
select A.a1,C.b1,C.b2
from my_data A, lateral (
select b1, b2 from Y where Y.id = A.id limit 1
) C
where A.b1 is null;
and it returns the expected result but I would like to know if there is a better way of writing it.
For example one iteration like:
select A.a1,B.b1,B.b2
from some_data A, lateral (
select b1, b2 from X where id = A.id limit 1
-- and if the query on 'X' fails then try:
select b1, b2 from Y where id = A.id limit 1
) B
any idea?
2will fall out of the LIMIT. If you want to be as efficient as possible, do not user ORDER BY, and be prepared for it to maybe blow up in some future version. – CL. Mar 21 '19 at 10:30SELECTif the first one returns any rows. See: https://dba.stackexchange.com/a/193914/3684, https://dba.stackexchange.com/a/184309/3684 – Erwin Brandstetter Mar 21 '19 at 10:45ORDER BYafterUNION ALL. That's logically impossible. – Erwin Brandstetter Mar 21 '19 at 16:16