SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL UNION Operator Tutorial

Example Tables

We will use the following tables named employees and managers for our examples:


    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        name VARCHAR(50),
        department VARCHAR(50)
    );

    CREATE TABLE managers (
        manager_id INT PRIMARY KEY,
        name VARCHAR(50),
        department VARCHAR(50)
    );

    INSERT INTO employees (employee_id, name, department) VALUES
    (1, 'Alice', 'HR'),
    (2, 'Bob', 'IT'),
    (3, 'Charlie', 'Finance');

    INSERT INTO managers (manager_id, name, department) VALUES
    (1, 'David', 'HR'),
    (2, 'Eva', 'IT'),
    (3, 'Frank', 'Finance');
    

Employees Table

employee_id name department
1 Alice HR
2 Bob IT
3 Charlie Finance

Managers Table

manager_id name department
1 David HR
2 Eva IT
3 Frank Finance

Using the SQL UNION Operator

The SQL UNION operator is used to combine the result sets of two or more SELECT statements. Each SELECT statement within the UNION must have the same number of columns in the result sets with similar data types.

Example: Combining Employees and Managers

To combine the names and departments of employees and managers:


    SELECT name, department FROM employees
    UNION
    SELECT name, department FROM managers;
    

Result:

Query SELECT name, department FROM employees UNION SELECT name, department FROM managers;
Result
  • Alice, HR
  • Bob, IT
  • Charlie, Finance
  • David, HR
  • Eva, IT
  • Frank, Finance

Example: Combining with UNION ALL

To include duplicate rows in the result set, use UNION ALL:


    SELECT name, department FROM employees
    UNION ALL
    SELECT name, department FROM managers;
    

Result:

Query SELECT name, department FROM employees UNION ALL SELECT name, department FROM managers;
Result
  • Alice, HR
  • Bob, IT
  • Charlie, Finance
  • David, HR
  • Eva, IT
  • Frank, Finance
  • Alice, HR
  • Bob, IT
  • Charlie, Finance