Consider two tables, employees and departments, with the following structures:
employees:
| employee_id | employee_name | department_id |
|-------------|---------------|---------------|
| 1 | Alice | 1 |
| 2 | Bob | 2 |
| 3 | Charlie | 1 |
| 4 | David | 3 |
departments:
| department_id | department_name |
|---------------|-----------------|
| 1 | Sales |
| 2 | Marketing |
| 3 | Finance |
Write an SQL query to list all employees along with their department names. If an employee does not belong to any department, the department name should be displayed as "No Department".
Solution:
SELECT e.employee_name, COALESCE(d.department_name, 'No Department') AS department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;
Explanation:
- We use a LEFT JOIN to ensure all rows from the
employeestable are included in the result, regardless of whether there is a matching row in thedepartmentstable. - The
COALESCEfunction is used to replaceNULLvalues in thedepartment_namecolumn with "No Department", which happens when an employee does not belong to any department. - We join the
employeestable with thedepartmentstable on thedepartment_idcolumn to match employees with their respective departments. - The
COALESCEfunction ensures that if there's no matching department for an employee, it will display "No Department" instead of aNULLdepartment name.
Share your alternate solution in comments.

