SQLEasyAggregation10 min

Departments with at least three employees

Return each non-NULL department ID containing at least three employees and its employee count. Return only the requested columns and follow the specified ordering. This question probes where filters input rows while having filters completed groups.

Input

Setup script defining employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT).

Output

department_id, employee_count; ascending department_id.

Constraints

0–10000 rows per table. IDs are unique and non-NULL unless stated otherwise; foreign keys may be NULL. Numeric amounts are integers from 0 to 1000000. Dates are valid YYYY-MM-DD text. Text uses case-sensitive comparison; test data has consistent case. Duplicate business values and NULLs are allowed unless excluded by the task.

Example

Tables and sample rows

CREATE TABLE employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT);
INSERT INTO employees VALUES (1,'Ana',10,NULL,100),(2,'Ben',10,1,200),(3,'Cara',20,1,200),(4,'Dan',20,3,300),(5,'Eve',NULL,NULL,NULL),(6,'Fin',10,NULL,100);

Expected result

department_id | employee_count
10 | 3

Another dataset (1)

CREATE TABLE employees(id INT, name VARCHAR(30), department_id INT, manager_id INT, salary INT);
INSERT INTO employees VALUES (1,'A',10,NULL,10),(2,'B',10,NULL,20),(3,'C',10,NULL,NULL);

Expected result

department_id | employee_count
10 | 3

Covers missing matches, ties, or NULL values without relying on insertion order.

Hints (2)
  1. Exclude NULL department IDs first.
  2. Use HAVING for the count threshold.

Target complexity: time O(n) · space O(n)

Your query

Checked instantly on your device with SQLite against 2 datasets. Rows must match the expected columns and order.

Reference solution

Sign in for solution
All SQL queries