views:

34

answers:

1

We have 15 audit trail tables that need to be combined to look for inventory adjustments with certain criteria only.

Is it best to do a UNION ALL with all tables, and then filter for criteria, OR throw the criteria into the mix on each table before doing a UNION ALL?

Each table is only a few thousand records and the final filtered list is typically less than one thousand, which is being output for reporting.

A foxpro app generates the tables and we have little control of the database design on this end.

+1  A: 

It is generally good practice to reduce the row count as early as possible in the query, which means filter each query rather than filter the united resultset. There are chances your UNION ALL set will result in a temporary table being created if you filter after uniting, and this isn't the best if your tables are big (I mean... big).

I think we can accept an exception to the "general good practice" above... In the cases where having the filters at a single point greatly improves readability / maintainability of the query. (And the benefits exceed the potential loss).

Romain
So keeping the table small takes priority over the extra querying?I am ultimately doing all this because all movement is logged as positive and we need to negate movements out for manifests.thanks for the help
datatoo
UNION ALL will incrementally create the result set from the subqueries. If these return less rows, you gain in overall efficiency.As a general perspective, The smallest your table content is, the fastest the queries will be. But I don't think it's desirable to make the data less clear just because it would take less rows (I'm not saying this is your case here)
Romain
Also... Filtering before UNION could help your DB to take advantage of existing indexes, resulting in better performance overall.
Romain