1. Left join with some example

2. inner join with some example

Bot GPT-4 Turbo Bot GPT-4 Turbo answered
7 months ago

A left join, also known as a left outer join, combines rows from two or more tables based on a related column between them but prioritizes the rows from the left table. It selects all records from the left table, and the matched records from the right table. If there is no match, the result is NULL on the right side.

Example of a Left Join in SQL:
Imagine we have two tables: `employees` and `departments`.

`employees` table:
```
+------------+----------+---------------+
| employee_id | name | department_id |
+------------+----------+---------------+
| 1 | Alice | 1 |
| 2 | Bob | 2 |
| 3 | Charlie | 3 |
| 4 | David | 4 |
+------------+----------+---------------+
```

`departments` table:
```
+---------------+---------------+
| department_id | department_name |
+---------------+---------------+
| 1 | HR |
| 2 | Marketing |
+---------------+---------------+
```

We want to retrieve a list of all employees and their respective departments, even if they don't have a department listed. We use a left join:

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

The result would be:
```
+----------+-----------------+
| name | department_name |
+----------+-----------------+
| Alice | HR |
| Bob | Marketing |
| Charlie | NULL |
| David | NULL |
+----------+-----------------+
```

Charlie and David do not have matching department_ids in the `departments` table, so their department_name is returned as NULL.

An inner join, also known simply as a join, combines rows from two or more tables based on a related column between them, but only includes rows that have a match in both tables.

Example of an Inner Join in SQL:
Using the same tables from the left join example, if we want to retrieve only the list of employees who have a department listed, we would use an inner join:

```sql
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
```

The result would be:
```
+----------+-----------------+
| name | department_name |
+----------+-----------------+
| Alice | HR |
| Bob | Marketing |
+----------+-----------------+
```

Only Alice and Bob are shown in the result, as they are the only employees with department_ids that have a corresponding match in the `departments` table. Charlie and David are excluded from the results because they don't match any record in the right table (`departments`).

🤔 🤔 Ask a New Question 🤔 🤔