Skip to content
Advertisement

Is there a way to make this SQL more efficient?

Consider the following tables:

department

deptid      (type:INT)
deptname    (type: TEXT)
hours       (type:INT)
active      (type:BIT)

employee

empid       (type:INT)
empname     (type: TEXT)
deptid      (type: INT)
designation (type: TEXT)
salary      (type: INT)

Write a query to return the columns empname and deptname of the employees belonging to those departments that have a head count of 4 or more. The records should be returned in alphabetical order of empname

This was my take:

SELECT e1.empname, d.deptname from employee AS e1
FULL JOIN department AS d on e1.deptid = d.deptid
  WHERE e1.deptid IN(
    SELECT deptid FROM(
      SELECT e2.deptid, COUNT(e2.empid)
      FROM employee AS e2
      GROUP BY e2.deptid
      HAVING COUNT(e2.empid) >= 4
    )
  )
ORDER BY empname;

How would you improve on this?

Advertisement

Answer

This is shorter and probably performs faster too

SELECT e1.empname, d.deptname
from (
      SELECT e2.deptid
      FROM employee AS e2
      GROUP BY e2.deptid
      HAVING COUNT(e2.empid) >= 4
    ) G
inner join employee AS e1 on e1.deptid = G.deptid
INNER JOIN department AS d on d.deptid = G.deptid
ORDER BY e1.empname;

Start with the grouping. You don’t need COUNT from the inner query. Then, join to both tables just to get the names.

INNER JOIN is used because once the count is complete, we already know that

  1. the employees exist
  2. the department exists
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement