Question

I have got two products tables, let's say current_products and historical_products, with the very same structure, and a key in the product_code field.

I have to search a list of product in these tables for further processing.

The trivial solution I've figured out is the following:

SELECT u.*
    , u.calculated_fields
    , t.other_fields
FROM (
    SELECT * FROM current_products
    UNION
    SELECT * FROM historical_products
) u
JOIN other_tables t
WHERE u.product_code = 'some_prodcut_code'
  • PROS: DRY

  • CONS: bad performance

The performance are not the best, so I would like to create a conditional query like this:

IF EXISTS (select * from current_products WHERE product_code = 'some_prodcut_code')
BEGIN
    SELECT u.*
        , u.calculated_fields
        , t.other_fields
    FROM current_products u
    JOIN other_tables t
    WHERE u.product_code = 'some_prodcut_code'
END
ELSE IF EXISTS (select * from historical_products WHERE product_code = 'some_prodcut_code')
BEGIN
    SELECT u.*
        , u.calculated_fields
        , t.other_fields
    FROM historical_products u
    JOIN other_tables t
    WHERE u.product_code = 'some_prodcut_code'
END
  • PROS: better performance

  • CONS: NOT DRY

QUESTION

Is there a third way?

Was it helpful?

Solution

performance killing you because you are pulling all records from both table first, THEN applying the where condition... try changing to

FROM (
    SELECT * FROM current_products
       WHERE product_code = 'some_prodcut_code'
    UNION
    SELECT * FROM historical_products
       WHERE product_code = 'some_prodcut_code'
) u
JOIN other_tables t

This way, the internal query can work against the indexes of the underlying products tables (presuming you HAVE an index on the product_code in the first position, or with other criteria you may want to also apply).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top