﻿ SQL: Find out the number of employees in each department

# SQL Exercises: Find out the number of employees in each department

## SQL Aggregate Functions: Exercise-25 with Solution

From the following table, write a SQL query to count the number of employees in each department. Return department code and number of employees.

Sample table: emp_details

``` EMP_IDNO EMP_FNAME       EMP_LNAME         EMP_DEPT
--------- --------------- --------------- ----------
127323 Michale         Robbin                  57
526689 Carlos          Snares                  63
843795 Enric           Dosio                   57
328717 Jhon            Snares                  63
444527 Joseph          Dosni                   47
659831 Zanifer         Emily                   47
847674 Kuleswar        Sitaraman               57
748681 Henrey          Gabriel                 47
555935 Alex            Manuel                  57
539569 George          Mardy                   27
733843 Mario           Saule                   63
631548 Alan            Snappy                  27
839139 Maria           Foster                  57
```

Sample Solution:

``````-- This query counts the number of employees in each department ('emp_dept') from the 'emp_details' table.
SELECT emp_dept, COUNT(*)
-- Specifies the table from which to retrieve the data (in this case, 'emp_details').
FROM emp_details
-- Groups the result set by the 'emp_dept' column.
GROUP BY emp_dept;
``````

Output of the Query:

```emp_dept		count
27			2
57			5
47			3
63			3
```

Code Explanation:

The given query in SQL retrieves the number of occurrences (count) of each unique value in the "emp_dept" column from the 'emp_details' table. The result will be a table with two columns: "emp_dept" and "COUNT()".
The "GROUP BY" clause groups the rows in the 'emp_details' table based on the values in the "emp_dept" column.

Relational Algebra Expression:

Relational Algebra Tree:

## Query Visualization:

Duration:

Rows:

Cost:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Calculate the total allotment for all departments.
Next SQL Exercise: SQL Formatting Output Exercises Home

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿