Types Of Joins in SQL

Types Of Joins in SQL

Introduction

  1. Joins are used to combine two or more tables together based on a common column.

  2. To use join we need to compulsorily have one or more columns common in both tables

Types Of Joins

  1. Cartesian Product / Cross Joins

    • This will return all possible combinations of the two tables

    • If table_1 has 3 rows and table_2 has 3 rows then in the newly formed table_final the number of rows = number of rows in table_1 number of rows in table_2 ie 3\3 = 9*

    • It is never used without any conditions because it will return all possible columns

    • Example--

        -- Create sample tables
        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            employee_name VARCHAR(255)
        );
      
        CREATE TABLE departments (
            department_id INT PRIMARY KEY,
            department_name VARCHAR(255)
        );
      
        -- Insert sample data
        INSERT INTO employees VALUES (1, 'Alice');
        INSERT INTO employees VALUES (2, 'Bob');
        INSERT INTO employees VALUES (3, 'Charlie');
      
        INSERT INTO departments VALUES (101, 'HR');
        INSERT INTO departments VALUES (102, 'IT');
      
        -- Perform a cross join
        SELECT *
        FROM employees
        CROSS JOIN departments;
      
        +-------------+------------------+------------------+-------------------+
        | employee_id | employee_name   | department_id    | department_name   |
        +-------------+------------------+------------------+-------------------+
        | 1           | Alice            | 101              | HR                |
        | 1           | Alice            | 102              | IT                |
        | 2           | Bob              | 101              | HR                |
        | 2           | Bob              | 102              | IT                |
        | 3           | Charlie          | 101              | HR                |
        | 3           | Charlie          | 102              | IT                |
        +-------------+------------------+------------------+-------------------+
      
  2. Inner Join

    • We will use Inner Join when in the final table we only want those columns which are a exact match

    • The rows are not matching based on the inner join we applied then the final output the table we will not have those rows

        -- Create sample tables
        CREATE TABLE employees (
            employee_id INT PRIMARY KEY,
            employee_name VARCHAR(255),
            department_id INT
        );
      
        CREATE TABLE departments (
            department_id INT PRIMARY KEY,
            department_name VARCHAR(255)
        );
      
        -- Insert sample data
        INSERT INTO employees VALUES (1, 'Alice', 101);
        INSERT INTO employees VALUES (2, 'Bob', 102);
        INSERT INTO employees VALUES (3, 'Charlie', 101);
      
        INSERT INTO departments VALUES (101, 'HR');
        INSERT INTO departments VALUES (102, 'IT');
      
        -- Perform INNER JOIN
        SELECT employees.employee_id, employees.employee_name, departments.department_name
        FROM employees
        INNER JOIN departments ON employees.department_id = departments.department_id;
      
        +-------------+------------------+-------------------+
        | employee_id | employee_name   | department_name   |
        +-------------+------------------+-------------------+
        | 1           | Alice            | HR                |
        | 2           | Bob              | IT                |
        | 3           | Charlie          | HR                |
        +-------------+------------------+-------------------+
      
  3. Left Join

    • All the rows which are matching in both the tables and also those rows which are not matching but present in the left table

    • Where rows are not matching we will have null values placed there

        -- Create sample tables
        CREATE TABLE students (
            student_id INT PRIMARY KEY,
            student_name VARCHAR(255)
        );
      
        CREATE TABLE grades (
            student_id INT,
            grade INT
        );
      
        -- Insert sample data
        INSERT INTO students VALUES (1, 'Alice');
        INSERT INTO students VALUES (2, 'Bob');
        INSERT INTO students VALUES (3, 'Charlie');
      
        INSERT INTO grades VALUES (1, 90);
        INSERT INTO grades VALUES (2, 85);
        -- Note: No grade for student_id 3
      
        -- Perform LEFT JOIN
        SELECT students.student_id, students.student_name, grades.grade
        FROM students
        LEFT JOIN grades ON students.student_id = grades.student_id;
      
        +-------------+------------------+-------+
        | student_id  | student_name     | grade |
        +-------------+------------------+-------+
        | 1           | Alice            | 90    |
        | 2           | Bob              | 85    |
        | 3           | Charlie          | NULL  |
        +-------------+------------------+-------+
      
  4. Right Join

    • All the rows which are matching in both the tables and also those rows which are not matching but present in the right table

    • Where rows are not matching we will have null values placed there

    SELECT column1, column2, ...
    FROM table1
    RIGHT JOIN table2 ON table1.column_name = table2.column_name;
    -- Perform RIGHT JOIN
    SELECT students.student_id, students.student_name, grades.grade
    FROM students
    RIGHT JOIN grades ON students.student_id = grades.student_id;
    +-------------+------------------+-------+
    | student_id  | student_name     | grade |
    +-------------+------------------+-------+
    | 1           | Alice            | 90    |
    | 2           | Bob              | 85    |
    | NULL        | NULL             | NULL  |
    +-------------+------------------+-------+
  1. Full Outer Join

    • All rows in the left table

    • All rows in the right table

    • Common rows between the two tables

    SELECT column1, column2, ...
    FROM table1
    FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
    -- Perform FULL OUTER JOIN
    SELECT students.student_id, students.student_name, grades.grade
    FROM students
    FULL OUTER JOIN grades ON students.student_id = grades.student_id;
    +-------------+------------------+-------+
    | student_id  | student_name     | grade |
    +-------------+------------------+-------+
    | 1           | Alice            | 90    |
    | 2           | Bob              | 85    |
    | 3           | Charlie          | NULL  |
    | NULL        | NULL             | NULL  |
    +-------------+------------------+-------+

Set Operation

  1. Union

    • When ever we want to vertically stack rows then we use union

    • The best use case example is when we want to merge table with itself

      • For example we have friendship table :

        if alice is friend of bob , then it is implied bob is a friend of alice, in given input table we only have alice being friend of bob , hence we need to stack bob and alice as friends as well then we use union

          CREATE TABLE friendships (
              user1_id INT,
              user2_id INT,
              PRIMARY KEY (user1_id, user2_id)
          );
        
          -- Insert sample data
          INSERT INTO friendships VALUES (1, 2);
          INSERT INTO friendships VALUES (2, 3);
          INSERT INTO friendships VALUES (1, 4);
        
          -- Use UNION to retrieve all friendships with details
          SELECT user1_id, user2_id FROM friendships
          UNION
          SELECT user2_id, user1_id FROM friendships;
        
          +---------+---------+
          | user1_id| user2_id|
          +---------+---------+
          |    1    |    2    |
          |    2    |    3    |
          |    1    |    4    |
          |    3    |    2    |  -- (this row is added due to UNION)
          |    4    |    1    |  -- (this row is added due to UNION)
          +---------+---------+
        

        Note: Union will remove duplicate rows and have only one single row

        if we want duplicates as well then use union all