Friday, September 18, 2015

SQL – Union vs. Union All – Which is better for performance?

UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
  • The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

Which is better for performance?
A UNION statement effectively does a SELECT DISTINCT on the results set.
If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Example
select Employees.FIRST_NAME from employees where EMPLOYEES.SALARY>1000 union
select Employees.FIRST_NAME from employees where  Employees.FIRST_NAME like 'M%';

SQL Tuning Advisor

Grant advisor to hr;
grant SELECT_CATALOG_ROLE to HR;
grant SELECT ANY DICTIONARY to HR;
ALTER system SET CONTROL_MANAGEMENT_PACK_ACCESS='DIAGNOSTIC+TUNING';

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...