Wednesday, December 18, 2024

SQL LEFT JOIN Keyword

 The LEFT JOIN keyword in SQL is used to retrieve data from two tables. It returns all records from the left table (the table mentioned before the JOIN clause), and the matched records from the right table (the table mentioned after the JOIN clause). If there is no match, the result is NULL on the side of the right table.

Syntax:

SELECT columns
FROM left_table
LEFT JOIN right_table ON left_table.column = right_table.column;

Example:

Suppose you have two tables: employees and departments.

employees table:

emp_id emp_name dept_id
1 John 101
2 Alice 102
3 Bob NULL

departments table:

dept_id dept_name
101 HR
102 Engineering

Now, if you want to list all employees and their corresponding departments (including employees without a department), you can use a LEFT JOIN:

SELECT employees.emp_id, employees.emp_name, departments.dept_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;

Result:

emp_id emp_name dept_name
1 John HR
2 Alice Engineering
3 Bob NULL

In this case, Bob doesn't have a department (dept_id is NULL), but the LEFT JOIN still includes him in the result with a NULL value in the dept_name column.

No comments:

Post a Comment