Skip to content

Optimalization of select containing Union

I have and easy select:

I would like to have account_id as input from another select and I did it this way:

How could be this optimalized to call select accound_id from ACCOUNTS where EMAIL like 'aa@aa.com' only once?

Advertisement

Answer

My first question is whether the union can be replaced by the union all. So, my first attempt would be to use exists and union all:

For this structure, you want an index on accounts(account_id, email). The exists simply looks up the values in the index. This does require scanning a and b.

If the query is returning a handful of rows and you want to remove duplicates, then union and replace union all. If it is returning a large set of rows — and there are not duplicates in each table and there is an easy way to identify the duplicates — then you can instead do:

User contributions licensed under: CC BY-SA
9 People found this is helpful