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 FULL OUTER JOIN Tutorial

Example Tables

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


    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(50),
        department_id INT
    );

    CREATE TABLE departments (
        department_id INT PRIMARY KEY,
        department_name VARCHAR(50)
    );

    INSERT INTO employees (employee_id, employee_name, department_id) VALUES
    (1, 'John Doe', 1),
    (2, 'Jane Smith', 2),
    (3, 'Emily Davis', NULL),
    (4, 'Michael Brown', 3);

    INSERT INTO departments (department_id, department_name) VALUES
    (1, 'HR'),
    (2, 'Finance'),
    (4, 'IT');
    

Employees Table

employee_id employee_name department_id
1 John Doe 1
2 Jane Smith 2
3 Emily Davis NULL
4 Michael Brown 3

Departments Table

department_id department_name
1 HR
2 Finance
4 IT

Using SQL FULL OUTER JOIN

The SQL FULL OUTER JOIN keyword returns all records when there is a match in either left (employees) or right (departments) table records. It means that if there are rows in the left table that do not have matches in the right table, or if there are rows in the right table that do not have matches in the left table, those rows will be included in the result set.

Example: Full Outer Join

To perform a full outer join on the employees and departments tables, use the following query:


    SELECT employees.employee_name, departments.department_name
    FROM employees
    FULL OUTER JOIN departments
    ON employees.department_id = departments.department_id;
    

Result:

employee_name John Doe
department_name HR
Jane Smith
Finance
Emily Davis
NULL
Michael Brown
NULL
NULL
IT