ORACLE UNION ALL
To combine the output sets of two or more Oracle SELECT statements, the Oracle UNION ALL operator is used. During the combining process, the UNION ALL operator does not remove the duplicate rows between the SELECT statements’ results, but returns all of them and this feature makes it different from the Oracle UNION operator.
There are however two mandatory conditions for using the UNION ALL operator in Oracle.
- Each SELECT statement must have the same number of expressions.
- Each corresponding expression in the different SELECT statement should be of the same data type.
SELECT expr_1, expr_2, ... expr_n FROM table1 WHERE conditions UNION ALL SELECT expr_1, expr_2, ... expr_n FROM table2 WHERE conditions;
expr_1, expr_2, … expr_n: It is used to specify the columns of the table which needs to be retrieved.
table1, table2: It is used to specify the name of the tables from which the records need to be retrieved.
conditions: It is used to specify the conditions to be strictly followed for selection.
STUDENT_ID STUDENT_NAME STUDENT_AGE 1 Joy 10 2 Smiley 13 3 Happy 11 4 James 13 5 Bond 10
TEACHER_ID TEACHER_NAME TEACHER_AGE 101 Tom 30 102 Jerry 25 103 James 40
SELECT student_id, student_age FROM students WHERE student_id > 2 UNION ALL SELECT teacher_id, teacher_age FROM teachers WHERE teacher_age >= 30;
STUDENT_ID STUDENT_AGE 3 11 4 13 5 10 101 30 103 40
The ‘students’ and the ‘teachers’ are already existing tables. After the union, the result of the UNION ALL operator will be same as that of UNION operator, since there are no duplicate rows between the selected corresponding fields.
STUDENT_ID STUDENT_NAME AGE 1 Joy 10 2 Smiley 13 3 Happy 11 4 James 13 5 Bond 10
TEACHER_ID TEACHER_NAME AGE 101 Tom 30 102 Jerry 25 103 James 40
SELECT student_name, age FROM students UNION SELECT teacher_name, age FROM teachers WHERE age >= 30 ORDER BY age;
STUDENT_NAME AGE Joy 10 Bond 10 Happy 11 James 13 Smiley 13 Tom 30 James 40
The ‘students’ and the ‘teachers’ are already existing tables. After the union, a group of the combination of student_id and teacher_id would appear along with another group of the combination of student_age and teacher_age. The corresponding column of the two tables is of the same data type. During this process, the duplicate sets will not be removed from the corresponding columns’ result. Here, the Union of the student_age column will be done only for the rows of the table ‘teachers’ with age greater than 30, while there is no condition for the union of teacher_name and student_name. The result will be finally available in the sorted order in the ascending sequence of the ages.