문제

I know the union all questions gets asked a lot, but I have a slight variation. I will be doing a union all on three different queries/tablesets. The first 2, by definition of their queries, will never have duplicates, but the third will definitely have duplicates.

My question is, does the order I do my union/union alls matter. For instance, should I do a UNION ALL on my first 2 tables that won't have duplicates (and never ever will) and then do a UNION to the third table since it will have duplicates? Or is the order better if its reversed? Or does it not matter?

Not a real pressing matter, just wondering if there was a best practice in this type of scenario.

도움이 되었습니까?

해결책

UNION ALL returns all rows, with no additional processing. A simple UNION sorts the entire row set to eliminate duplicates. While the optimizer may be able to figure everything out by studying the indices and constraints, you can always give it a little hand like this:

  select * from table1
union all
  select * from table2
union all
  select *
  from (
    SELECT DISTINCT * from table3
  ) T

This ensures that the sort-and-eliminate-duplicates is only performed on table3.

Anytime intent can be simply and clearly communicated better to both human users and compilers, that is almost certainly the correct way to write the code. In this case performance may also be enhanced, and cannot be degraded.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top