Exercise 1
intermediateQuestion
List all employees and their departments, including employees without a department.
Table Schema
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT
);
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(100)
);Show Solution
Solution
1SELECT e.name AS employee, d.name AS department
2FROM employees e
3LEFT JOIN departments d ON e.department_id = d.id;Expected Output
| employee | department | |---|---| | John | Sales | | Jane | NULL |
Explanation
LEFT JOIN returns all rows from the left table and matching rows from the right. Unmatched right-side rows show as NULL.