I have 'inherited' a database application (based on an Oracle 10g database and written in Delphi), which has to make several decisions as follows:
Do Query1.
If the result set is empty, do Query2.
The queries are SELECT queries having the same output columns and sometimes similar (Case 1) and sometimes different (Case 2) input (FROM) and conditions (WHERE).
Case 1: Sometimes the difference is: col like 'x' (or col = 'x') becomes col like '%'.
- Performance: it probably would be best to use two different queries (
col = 'x'and the other query without it). - Maintainability:
col like :paramis better as it does not need 2 queries - Compromise solution:
AND (col = 'x' OR :param = 1)
Case 2: Another time I have to use a completly different Query2 if there is no data in the resultset of Query1.
From searching stackoverflow and the internet I am aware of several solutions to my problem:
Using two SQL queries: Let the program do the work instead of the database (but needs to query the database twice instead of only once)
result = executeQuery(Query1) if (isEmpty(result)) result = executeQuery(Query2)Using UNION: Let Oracle do all the work (but needs to execute Query1 twice):
Query1 UNION ALL Query 2 WHERE NOT EXISTS (Query 1)Using PL/SQL: Let Oracle do most of the work (but I read somewhere that the queries are compiled each time this way)
begin Query1; exception when no_data_found then Query2; end;
My questions are:
- Are there other (better) solutions?
- What would you (as a more experienced database user than me) use?
- What are the (dis)advantages?
- What are the caveats?