Geek Slack

Getting Started with SQL Server
    About Lesson


    SQL RIGHT JOIN Keyword


    SQL RIGHT JOIN Keyword

    The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side if there is no match.

    Syntax

    SELECT columns
    FROM table1
    RIGHT JOIN table2
    ON table1.common_column = table2.common_column;

    Example: RIGHT JOIN

    SELECT employees.name, departments.department_name
    FROM employees
    RIGHT JOIN departments
    ON employees.department_id = departments.id;

    This query selects department names and their corresponding employee names. It returns all departments, and the employee name will be NULL if there is no matching employee.

    Sample Tables

    Consider the following two tables:

    Employees Table

    | id | name        | department_id |
    |----|-------------|---------------|
    | 1  | John Doe    | 1             |
    | 2  | Jane Smith  | 2             |
    | 3  | Mike Johnson| 1             |
    | 4  | Emily Davis | 3             |

    Departments Table

    | id | department_name |
    |----|-----------------|
    | 1  | HR              |
    | 2  | Sales           |
    | 3  | IT              |
    | 4  | Marketing       |

    Result of RIGHT JOIN

    | name        | department_name |
    |-------------|-----------------|
    | John Doe    | HR              |
    | Mike Johnson| HR              |
    | Jane Smith  | Sales           |
    | Emily Davis | IT              |
    | NULL        | Marketing       |

    All departments are returned. Marketing has no matching employee, so name is NULL.