Example: JOIN Queries
Example: JOIN Queries Using Two Tables
We will use a Company Database with two tables:
-
employees
-
departments
1. Create Tables
2. Insert Sample Data
3. JOIN Queries With Outputs
3.1 INNER JOIN: Employees With a Department
Output
| emp_id | emp_name | salary | dept_name |
|---|---|---|---|
| 1 | Alice | 50000 | Human Resources |
| 2 | Bob | 60000 | Finance |
| 3 | Charlie | 70000 | Engineering |
| 4 | David | 55000 | Engineering |
(Eva is excluded because she has no dept_id)
3.2 LEFT JOIN: All Employees + Department (if any)
Output
| emp_id | emp_name | salary | dept_name |
|---|---|---|---|
| 1 | Alice | 50000 | Human Resources |
| 2 | Bob | 60000 | Finance |
| 3 | Charlie | 70000 | Engineering |
| 4 | David | 55000 | Engineering |
| 5 | Eva | 65000 | NULL |
(Eva appears with NULL since she has no department)
3.3 RIGHT JOIN: All Departments + Employees (if any)
(Useful when some departments have no employees)
Output
| emp_id | emp_name | dept_name |
|---|---|---|
| 1 | Alice | Human Resources |
| 2 | Bob | Finance |
| 3 | Charlie | Engineering |
| 4 | David | Engineering |
| NULL | NULL | Marketing |
(Marketing dept has no employees)
3.4 FULL OUTER JOIN (MySQL simulation)
Output
| emp_id | emp_name | dept_name |
|---|---|---|
| 1 | Alice | Human Resources |
| 2 | Bob | Finance |
| 3 | Charlie | Engineering |
| 4 | David | Engineering |
| 5 | Eva | NULL |
| NULL | NULL | Marketing |
4. Additional Useful JOIN Queries
4.1 Employees with salary > 55000 and their department
4.2 Count of employees in each department
4.3 Departments having no employees
Comments
Post a Comment