Skip to content
Advertisement

How to get the department name in this tutorial sql query?

Following the tutorial on SQL here I want to query the number of employees per department together with the department name.

I tried the following query in that tutorial:

SELECT count(*), dept_name
FROM employees, departments
WHERE employees.dept_id = departments.dept_id
GROUP BY departments.dept_id

but it returns

COUNT(*)    dept_name
2           NULL
2           NULL

instead of the expected output

COUNT(*)    dept_name
2           Accounting
2           Sales

What am I doing wrong here?

Advertisement

Answer

Group by dept_name not dept_id

SELECT count(*), dept_name
FROM employees, departments
WHERE employees.dept_id = departments.dept_id
GROUP BY departments.dept_name

And you can better use join like Juan Carlos Oropeza‘s answer:

SELECT count(*), dept_name
FROM employees JOIN departments ONemployees.dept_id = departments.dept_id
GROUP BY departments.dept_name

enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement