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.

Hints

0
Ā 
Test Case

Input:

Department
Employee