How do you implement a FULL OUTER JOIN to combine rows from two tables and include all rows from both sides?
Posted by TinaGrn
Last Updated: June 13, 2024
To implement a FULL OUTER JOIN in SQL, you will combine rows from two tables based on a related column, including all rows from both tables regardless of whether there is a match or not. If there are no matches in one of the tables, the result will include NULL values for those columns. Here's the general syntax for a FULL OUTER JOIN:
SELECT 
    columns
FROM 
    table1
FULL OUTER JOIN 
    table2 
ON 
    table1.common_column = table2.common_column;
Steps to Create a FULL OUTER JOIN
1. Identify the Tables: Determine the two tables you want to join, say table1 and table2. 2. Identify the Common Column: Find the column that the tables have in common that will be used for the join condition. 3. Write the SQL Query: Use the FULL OUTER JOIN syntax, specifying the appropriate columns you want to select.
Example Scenario
Consider two tables, employees and departments. employees table: | employee_id | name | department_id | |-------------|------------|----------------| | 1 | Alice | 10 | | 2 | Bob | 20 | | 3 | Charlie | NULL | departments table: | department_id | department_name | |---------------|------------------| | 10 | HR | | 20 | Engineering | | 30 | Marketing |
FULL OUTER JOIN Query
To combine these two tables and include all employees and all departments, you could use a query like this:
SELECT 
    e.employee_id,
    e.name,
    e.department_id,
    d.department_name
FROM 
    employees e
FULL OUTER JOIN 
    departments d 
ON 
    e.department_id = d.department_id;
Result Set
The result of the above query would look like this: | employee_id | name | department_id | department_name | |-------------|------------|----------------|------------------| | 1 | Alice | 10 | HR | | 2 | Bob | 20 | Engineering | | 3 | Charlie | NULL | NULL | | NULL | NULL | 30 | Marketing |
Explanation
- Rows from employees: The row for Charlie appears with NULL values in the department columns since he does not belong to a department. - Rows from departments: The row for the Marketing department appears with NULL values in the employee columns since there are no employees in that department. - Matched Rows: Rows from both tables that have matching department IDs appear with values from both tables. This method ensures that all data from both tables are represented in the result set, which is the key feature of a FULL OUTER JOIN.