SQL Server’s UNION and INTERSECT are powerful tools for combining query results, but they behave differently—UNION merges all matching rows (duplicates removed), while INTERSECT returns only rows present in both result sets. Without these, you’d need manual loops or joins, which are slower and harder to read. Here’s how to use them correctly, step by-step, with real-world examples.
What You’ll Need
- SQL Server (Express, Standard, or Enterprise; latest version preferred).
- A database with sample tables (e.g., `Employees`, `Departments`).
- Basic SQL knowledge of joins, SELECT, and WHERE clauses.
- A text editor or SQL client (e.g., SQL Server Management Studio, SSMS, or T-SQL in PowerShell).
Step-by-Step: Combining Queries with UNION and INTERSECT
- Create Sample Tables Run these T-SQL commands to create tables with overlapping data (e.g., employees from two departments).
- Use UNION to Merge Results UNION combines all rows from both queries, ignoring duplicates. Example: List all employees from HR or Finance departments.
- Add UNIQUE to Preserve Duplicates If duplicates matter (e.g., tracking duplicates in analytics), use UNION ALL instead.
- Use INTERSECT for Common Data INTERSECT returns only rows that exist in both queries. Example: Find employees paid over $70,000 in both HR and Finance.
- Optimize with Aliases and WHERE For complex queries, alias tables and filter results early to speed up execution.
- Test with DISTINCT if Needed If UNION returns unexpected duplicates (e.g., from NULL comparisons), use DISTINCT.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
DepartmentID INT,
Salary DECIMAL(10,2)
);
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
Name NVARCHAR(100)
);
-- Insert sample data (e.g., overlapping employees)
INSERT INTO Departments VALUES (1, 'HR'), (2, 'Finance');
INSERT INTO Employees VALUES
(101, 'Alice', 1, 60000),
(102, 'Bob', 2, 75000),
(103, 'Charlie', 1, 55000),
(104, 'Diana', 2, 80000);
SELECT Name, DepartmentID FROM Employees WHERE DepartmentID = 1
UNION
SELECT Name, DepartmentID FROM Employees WHERE DepartmentID = 2;
Output: Alice, 1, Charlie, 1, Bob, 2, Diana, 2. Note duplicates (e.g., if an employee were in both tables) are removed.
SELECT Name FROM Employees WHERE EmployeeID = 101
UNION ALL
SELECT Name FROM Employees WHERE EmployeeID = 102;
SELECT EmployeeID FROM Employees WHERE Salary > 70000
INTERSECT
SELECT EmployeeID FROM Employees WHERE DepartmentID IN (1, 2)
Output: 102 (Bob) since he meets both criteria. No rows for Alice/Diana.
WITH HighPaid AS (SELECT EmployeeID FROM Employees WHERE Salary > 70000),
FinanceEmployees AS (SELECT EmployeeID FROM Employees WHERE DepartmentID = 2)
SELECT e.Name FROM HighPaid h
INTERSECT
SELECT f.Name FROM FinanceEmployees f;
SELECT * FROM Employees WHERE DepartmentID = 1
UNION DISTINCT
SELECT * FROM Employees WHERE DepartmentID = 2;
Common Mistakes
- Forgetting Column Order UNION requires identical column counts and data types. Mismatches throw errors. Fix: Add/remove columns or use AS aliases.
- Ignoring NULLs UNION treats NULLs as distinct values. To exclude them, add WHERE NOT EXISTS NULL checks or use DISTINCT.
- Overusing UNION ALL Without UNIQUE, UNION ALL is faster but still removes duplicates. Reserve it for performance-critical scenarios.
- Misinterpreting INTERSECT INTERSECT is NOT a set operation like SQL’s `AND`. It compares rows row-by-row, not filtered sets.
- Not Indexing Key Columns Queries with UNION or INTERSECT often scan tables. Add indexes on WHERE conditions (e.g., `DepartmentID`, `Salary`).
Tips
- Use SET Operations for Complex Logic Combine UNION with EXISTS or subqueries to filter combined results dynamically. Example: List all employees in HR *or* Finance with salary > $60,000.
SELECT Name FROM Employees WHERE DepartmentID IN (1, 2) AND Salary > 60000;
CREATE TABLE #TempEmployees (Name NVARCHAR(100)); INSERT INTO #TempEmployees SELECT Name FROM Employees WHERE DepartmentID = 1 UNION ALL SELECT Name FROM Employees WHERE DepartmentID = 2;
Troubleshooting
If UNION or INTERSECT fails:
- Check Syntax Errors Start with a simple query (e.g., UNION two single-row SELECTs) before adding complexity. Fix syntax issues first (e.g., missing commas, mismatched parentheses).
- Verify Column Counts Run each query individually to confirm column counts match. Use the meta-data view (e.g., `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS`) to compare.
- Test with Minimal Data Replace sample data with a single row to isolate whether the issue is data-related (e.g., NULLs, duplicates).
- Enable Execution Plan In SSMS, right-click the query > "Execution Plan." Look for "Hash Match" or "Nested Loops" for INTERSECT, or "Merge Join" for UNION. High cardinality or missing indexes may slow performance.
- Restart SQL Server If performance degrades over time, restart SQL Server Services to clear locks or memory bloat. For large datasets, consider partitioning the table.
- Replicate in Another Database Test in a non-production database (e.g., Azure SQL Test DB) to rule out environment-specific issues (e.g., permissions, collation settings).
Frequently Asked Questions
1. Why does UNION remove duplicates by default?
UNION is designed to return unique rows to avoid redundancy. Use UNION ALL to preserve duplicates (e.g., for analytics like "total unique employees + duplicates").
2. What’s the difference between UNION vs UNION ALL?
UNION removes duplicates and sorts results (unless ORDER BY is used). UNION ALL is faster but keeps duplicates. Choose based on whether duplicates matter.
3. Can I use UNION with GROUP BY?
No. UNION breaks GROUP BY logic. Replace with JOINs, subqueries, or CTEs for aggregated results.
4. How do I optimize a slow INTERSECT query?
Add indexes on joined columns (e.g., `EmployeeID`). Avoid correlated subqueries by pre-filtering data in CTEs or temp tables. Use EXPANDER in SSMS to visualize the plan.
5. What if my UNION returns NULLs differently?
NULLs act as distinct values. Use IS NULL/IS NOT NULL in WHERE clauses or cast columns to the same type (e.g., `CAST(col AS INT)`).
6. Should I use INTERSECT or JOIN for set overlap?
For simple overlap checks, JOINs are often clearer and perform better. INTERSECT is less intuitive and can be slower for large datasets.