I basically have 2 queries to return data, the first query is fast but doesn't work in 5% of cases, the second query works for all cases but is a lot slower
How to code it in a way that it always returns a result but avoids running the second query if the first query produces a result? By result I mean anything between one row and 1000 rows
My current query which only runs the first query and returns an empty result set looks like the following:
SELECT CASE WHEN x.column1 IS NOT NULL THEN x.column1 ELSE y.column1 END column1,
CASE WHEN x.column1 IS NOT NULL THEN x.column2 ELSE y.column2 END column2
FROM (SELECT column1, column2 FROM mytable WHERE < 1st SET OF complex conditions >) x
, (SELECT column1, column2 FROM mytable WHERE < 2nd SET OF complex conditions >) y
By complex conditions I mean a series of GIS functions such as st_intersects and st_dwithin that would baloon this question. The output is the same for both queries when the first one returns something. I can't run both at the same time otherwise it runs for too long and users time out.
My current query is not registering the x.column1 not returning anything, and because of that the set of conditions returned by the y query are never taken into account, how to fix this?
Edit: again the intended result is when query1 (represented by x) produces an empty result set, I need to take results from running query2 (represented by y).