Union is inefficient because it requires repeated value scanning. If the merge operation does not intentionally delete duplicate rows, use Union all
The number of fields in the two SQL statements to be combined must be the same, and the field type must be "compatible" (Consistent );
If we need to display the results of two select statements as a whole, we need to use the Union or union all keywords. Union (or union) is used to display multiple results together.
The difference between Union and Union all is that union will automatically compress the repeated results in multiple result sets, while union all will display all the results, whether they are repeated or not.
Union: Perform Union operations on two result sets, excluding duplicate rows and sorting by default rules;
Union all: Perform Union operations on two result sets, including duplicate rows without sorting;
Intersect: intersection of two result sets, excluding duplicate rows, and sorting by default rules;
Minus: performs the Difference Operation on two result sets, excluding duplicate rows, and sorts the default rules at the same time.
You can specify the order by clause in the last result set to change the sorting method.
For example:
Select employee_id, job_id from employees union select employee_id, job_id from job_history
The above two tables are joined together. The two examples compress the duplicate values in the results of the two select statements, that is, the result data is not the sum of the two results. If you want to use Union all even if repeated results are displayed, for example:
2. The Scott user in Oracle has many duplicate values in the table EMP select * from EMP where deptno> = 20 Union all select * from EMP where deptno <= 30.
Note the following when using the Union and Union all keywords:
Union and Union all can combine multiple result sets, not just two. You can concatenate multiple result sets. When using Union and Union all, you must ensure that the results of each select set have the same number of columns, and each column has the same type. But the column names do not need to be the same. Oracle uses the column name of the first result as the column name of the result set. The following is an example: Select empno, ename from EMP Union select deptno, dname from Dept. We do not need to use the order by clause in each select result set for sorting, we can use an order by statement to sort the entire result. Example: Select empno, ename from EMP Union select deptno, dname from Dept order by ename;
Difference between Union and Union all