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

  1. Create Sample Tables Run these T-SQL commands to create tables with overlapping data (e.g., employees from two departments).
  2. 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);
      
  3. Use UNION to Merge Results UNION combines all rows from both queries, ignoring duplicates. Example: List all employees from HR or Finance departments.
  4. 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.

  5. Add UNIQUE to Preserve Duplicates If duplicates matter (e.g., tracking duplicates in analytics), use UNION ALL instead.
  6. SELECT Name FROM Employees WHERE EmployeeID = 101
        UNION ALL
        SELECT Name FROM Employees WHERE EmployeeID = 102;
  7. 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.
  8. 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.

  9. Optimize with Aliases and WHERE For complex queries, alias tables and filter results early to speed up execution.
  10. 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;
  11. Test with DISTINCT if Needed If UNION returns unexpected duplicates (e.g., from NULL comparisons), use DISTINCT.
  12. 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;
  • Profile Performance Run EXEC sp_who2 in SSMS to check query plans. UNION can be expensive on large datasets—consider alternative join-based approaches.
  • Document Assumptions If UNION ALL includes duplicates, label it clearly in documentation (e.g., "Returns all records, including duplicates").
  • Leverage Temp Tables For repeated UNIONs, store results in temp tables to avoid recomputation.
  • 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;
  • Avoid UNION in Aggregations UNION breaks GROUP BY or HAVING clauses. Replace with JOINs or CTEs for aggregated results.

Troubleshooting

If UNION or INTERSECT fails:

  1. 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).
  2. 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.
  3. Test with Minimal Data Replace sample data with a single row to isolate whether the issue is data-related (e.g., NULLs, duplicates).
  4. 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.
  5. 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.
  6. 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.