Ticker

6/recent/ticker-posts

Left Join in SQL Server

Left Join in SQL Server

Introduction:
The Left Join is one of the types of joins in SQL Server that allows you to combine rows from two or more tables based on a related column. It retrieves all the rows from the left table and matching rows from the right table. If there are no matching rows in the right table, NULL values are returned for the columns from the right table.

Syntax:

sql
SELECT column_list
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Explanation:

  • SELECT column_list: Specifies the columns you want to retrieve from the tables. You can use * to select all columns or provide a list of specific column names.

  • table1: The left table in the join operation, from which all rows will be retrieved.

  • LEFT JOIN: Specifies the type of join you want to perform. In this case, it's a Left Join.

  • table2: The right table in the join operation, from which matching rows will be retrieved.

  • ON table1.column_name = table2.column_name: The condition that specifies how the two tables are related. It defines the columns used for matching rows between the left and right tables.

Example:
Consider two tables, employees and departments, with the following data:

Table: employees

emp_idemp_namedepartment_id
1John101
2Jane102
3Mike101
4Sarah103

Table: departments

department_iddepartment_name
101HR
102Finance
103Marketing

Query:

sql
SELECT emp_name, department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;

Result:

emp_namedepartment_name
JohnHR
JaneFinance
MikeHR
SarahMarketing

Explanation:
In the above example, we used a Left Join to combine the employees and departments tables based on the department_id column. All rows from the employees table were retrieved, and matching department names from the departments table were included. Since there's no matching department for Sarah in the departments table, the department_name column contains NULL for her record.

Post a Comment

0 Comments