Answer: UNION Set Operator
Find a detailed explanation of using UNION in SQL.
Solution
The solution is given below:
MySQL
/* The query to use UNION to combine result sets */SELECT EmpName, ProjectNameFROM Employees AS EJOIN Projects AS P ON E.EmpID = P.EmpIDUNIONSELECT 'No Employee Assigned' AS EmpName, ProjectNameFROM ProjectsWHERE EmpID IS NULLORDER BY EmpName DESC, ProjectName ASC;
Code explanation
The explanation of the solution code is given below:
Line 2: The
SELECTquery selectsEmpNameandProjectNamefromEmployeesandProjects, respectively.Line 3: The data is retrieved from the
Employeestable. We useASto set an alias for the tables.Line 4: A
JOINoperation is applied withProjectsto combine the data based on theEmpIDcolumn.Line 5: The
UNIONkeyword is used to combine the results of two queries.Line 6: This part selects projects that currently have no employee linked to them and it renames ‘No Employee Assigned’ in
EmpName.Line 7: The data is retrieved from the
Projectstable.Line 8: The
WHEREclause ...
Ask