Since at most 1 row per view seems to be given, there is a very simple and cheap solution:
-- CREATE VIEW contributors AS
TABLE current_campaign
UNION ALL
TABLE last_campaign -- assuming matching row type
LIMIT 1; -- applies to the whole query
If that was an over-simplification:
-- CREATE VIEW contributors AS
SELECT * FROM current_campaign
WHERE ...
UNION ALL
SELECT * FROM last_campaign
WHERE ...
LIMIT 1;
It would be a waste of time to count rows in current_campaign
or run an EXISTS
semi-join, since LIMIT 1
does everything you need automatically. Postgres stops executing as soon as enough rows are found to satisfy the LIMIT
(1 in this case). You'll see "(never executed)" in the output of EXPLAIN ANALYZE
for any later SELECT
in the list. See links below for more.
This is an implementation detail that only works for UNION ALL
(not UNION
) and without an outer ORDER BY
or other clauses that would force Postgres to consider all rows. I would expect other RDBMS to behave the same, but I only know about Postgres. It's guaranteed to work in all versions up to the current 9.5.
About the short syntax TABLE current_campaign
:
Related, with more explanation, the same a bit more verbose: