Oracle SQL study materials
Oracle SQL study resources

Oracle SQL: Using Set Operators

Oracle SQL · Work through your exam, one topic at a time.

All guide sections

Using Set Operators

The four operators

UNION combines two result sets and removes duplicates. UNION ALL keeps every row including duplicates and is the cheapest option. INTERSECT returns rows present in both. MINUS returns rows from the first query that are not in the second - order matters and MINUS is not commutative.

Rules that questions test

Both queries must return the same number of columns, and corresponding columns must be in compatible data type groups. Column headings come from the first query only. ORDER BY may appear only once, at the very end, and must reference columns by the first query's names or by position. Duplicate elimination treats two NULLs as equal, unlike a WHERE comparison.

The operators are evaluated left to right (or by parentheses) at the same precedence level - there is no AND/OR-style hierarchy among them. Each SELECT may have its own WHERE, GROUP BY, and HAVING.

Traps

Using UNION when UNION ALL is intended silently removes duplicates. Mismatched column counts raise ORA-01789; incompatible types raise ORA-01790. Putting ORDER BY on the first query is a syntax error. MINUS backwards gives a plausible but wrong answer - check which side holds the rows you want to keep. LOB and long columns are not allowed.

Worked example

SELECT employee_id FROM employees MINUS SELECT employee_id FROM job_history; This returns employees with no recorded job history. Reversing the operands would answer a different question entirely.

Rule of thumb

Set operators compare whole rows: matching column counts, aligned types, and headings inherited from query one.