Ticker

6/recent/ticker-posts

Right Join in SQL

Right Join in SQL


Overview: The RIGHT JOIN is a type of join operation in SQL that retrieves all records from the right table and the matched records from the left table. It combines rows from both tables based on a related column between them.

Syntax:

sql
SELECT column_list FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;

Explanation: In the syntax above:

  • table1 and table2 are the names of the tables to be joined.
  • column_list represents the columns to be retrieved from the joined tables.
  • ON specifies the condition for joining the tables based on a common column.

When the RIGHT JOIN is used, the result set contains all records from the right table and only the matching records from the left table. If there is no match, NULL values are returned for the columns from the left table.

Example: Consider the following two tables: Employees and Departments.

Employees:

EmployeeIDFirstNameLastNameDepartmentID
1JohnSmith1
2JaneDoe2
3DavidJohnson1
4LisaBrown3

Departments:

DepartmentIDDepartmentName
1Sales
2Marketing
3Finance

To retrieve all employees and their corresponding department names, you can use a RIGHT JOIN as follows:

sql
SELECT Employees.EmployeeID, Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

Output:

EmployeeIDFirstNameLastNameDepartmentName
1JohnSmithSales
2JaneDoeMarketing
3DavidJohnsonSales
NULLNULLNULLFinance

In the result set, you can observe that all the employees are included, and the department name is displayed for each employee. However, since the Finance department does not have any associated employees, NULL values are shown for the columns from the Employees table.

Post a Comment

0 Comments