76. Employees and Their Departments
A company stores information about its employees and departments.
Some departments may exist even if no employees are currently assigned to them.
You are given two tables:
Employee Table
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā employee_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā name ā varchar ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā dept_id ā int ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- employee_id is the primary key
- dept_id indicates the department an employee belongs to
Department Table
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā dept_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā dept_name ā varchar ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- dept_id is the primary key
- Each row represents a department
Write an SQL query to return all departments, including those without any employees.
For departments without employees, display NULL for employee details. The result can be returned in any order.
Example 1:
Input:
Employee:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā¦āāāāāāāāāāā ā employee_id ā name ā dept_id ā ā āāāāāāāāāāāāāā¬āāāāāāāāāāā¬āāāāāāāāāā⣠ā 1 ā Alice ā 10 ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāā ā 2 ā Bob ā 20 ā āāāāāāāāāāāāāāā©āāāāāāāāāāā©āāāāāāāāāāā
Department:
āāāāāāāāāāāā¦āāāāāāāāāāāā ā dept_id ā dept_name ā ā āāāāāāāāāāā¬āāāāāāāāāāā⣠ā 10 ā HR ā āāāāāāāāāāāā¼āāāāāāāāāāāā ā 20 ā IT ā āāāāāāāāāāāā¼āāāāāāāāāāāā ā 30 ā Finance ā āāāāāāāāāāāā©āāāāāāāāāāāā
Output:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā¦āāāāāāāāāāāā ā employee_id ā name ā dept_name ā ā āāāāāāāāāāāāāā¬āāāāāāāāāāā¬āāāāāāāāāāā⣠ā 1 ā Alice ā HR ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāāā ā 2 ā Bob ā IT ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāāā ā NULL ā NULL ā Finance ā āāāāāāāāāāāāāāā©āāāāāāāāāāā©āāāāāāāāāāāā
Explanation:
Finance department exists but has no employees, so employee fields are NULL.
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.