List all the departments that don’t have any employees

  • Hi,

    I have Department Table having DepartmentId,Departmentname columns and Employee Table having EmployeeId,EmployeeName,DepartmentId.

    I have to Display List all the departments that don’t have any employees(Without using sub query).

    Please do reply as soon as possible.

    Thanks,

    Chow.

  • Please post your DDL and some sample data in the format outlined in the following article:

    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    That will help us to solve your problem for you 🙂

  • naidussdba (10/29/2008)


    I have to Display List all the departments that don’t have any employees(Without using sub query).

    So why this unusual restriction?

    [font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
    Proactive Performance Solutions, Inc.
    [/font]
    [font="Verdana"] "Performance is our middle name."[/font]

  • This should do it:

    Select DepartmentId, Departmentname

    From Department

    Left Outer Join Employee ON Employee.DepartmentID = Department.DepartmentID

    Where Employee.DepartmentID IS NULL

    [font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
    Proactive Performance Solutions, Inc.
    [/font]
    [font="Verdana"] "Performance is our middle name."[/font]

  • rbarryyoung (10/29/2008)


    naidussdba (10/29/2008)


    I have to Display List all the departments that don’t have any employees(Without using sub query).

    So why this unusual restriction?

    Becuase it is an interview question 😉


    Madhivanan

    Failing to plan is Planning to fail

  • Madhivanan (10/30/2008)


    rbarryyoung (10/29/2008)


    naidussdba (10/29/2008)


    I have to Display List all the departments that don’t have any employees(Without using sub query).

    So why this unusual restriction?

    Becuase it is an interview question 😉

    Or a homework question 😛

  • I would group by department having count(*) = 0.

  • Ian Massi (10/31/2008)


    I would group by department having count(*) = 0.

    won't the count be equal to or greater than 1 always? if the count is 0, then it doesn't exist

    I guess if you did a left join a did a count on the employeeid which a count(null) = 0? since null's are excluded from aggrigate functions?

    probably still faster to do there left join where emp.deptid is null since it won't require grouping everything together.

  • Oh yeah, what on Earth was I thinking! The left outer join was definitely the way to go.

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply