SQL Exercise: List the department where at least two employees work
SQL employee Database: Exercise-98 with Solution
[An editor is available at the bottom of the page to write and execute the scripts.]
98. From the following table, write a SQL query to identify the departments in which at least two employees are employed. Return department id, number of employees.
Sample table: employees
Sample Solution:
SELECT dep_id,
count(*)
FROM employees
GROUP BY dep_id
HAVING count(*) >= 2;
Sample Output:
dep_id | count --------+------- 3001 | 6 1001 | 3 2001 | 5 (3 rows)
Explanation:
The given query in SQL that retrieves the count of employees in each department, but only for those departments that have two or more employees from the table 'employees'.
It groups the results by the "dep_id" column, and counts the number of records for each unique value of "dep_id".
The HAVING clause filters the results to include only those groups where the count of records is greater than or equal to 2.
Relational Algebra Expression:
Relational Algebra Tree:
Practice Online
Sample Database: employee
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Number of employee for each job in each department.
Next SQL Exercise: Grade, number of employees, and salary for each grade.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/sql-exercises/employee-database-exercise/sql-employee-database-exercise-98.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics