w3resource

SQL Exercise: Number of employees equals to department length

SQL subqueries on employee Database: Exercise-41 with Solution

[An editor is available at the bottom of the page to write and execute the scripts.]

41. From the following tables, write a SQL query to find those departments where the number of employees is equal to the number of characters in the department name. Return complete information about the employees.

Sample table: employees


Sample table: department


Sample Solution:

SELECT *
FROM department d
WHERE length(dep_name) IN
    (SELECT count(*)
     FROM employees e
     WHERE e.dep_id = d.dep_id );

OR

SELECT d.dep_name,
       count(*)
FROM employees e,
     department d
WHERE e.dep_id = d.dep_id
GROUP BY d.dep_name
HAVING count(*) = LENGTH (d.dep_name);

Sample Output:

 dep_id | dep_name | dep_location
--------+----------+--------------
   2001 | AUDIT    | MELBOURNE
(1 row)

Explanation:

The said query in SQL that selects all departments from the departments table where the length of the department name is equal to the number of employees in that department.

The WHERE clause filters the results to only include departments where the length of the dep_name is equal to the number of employees in that department.

The inner query is a subquery that returns the count of employees for each department.

The IN operator is used to compare the result of the subquery to the length of the department name in the outer query.

Practice Online


Structure of employee DataBase:

employee database structure

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

Previous SQL Exercise: List employees whose netpay is more than others.
Next SQL Exercise: List departments with the most employees.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.