Helix Systems' HR dashboard materializes headcount and earliest-hire metrics per department into a temp table to support multiple workforce reports in the same session.
Write a query to return the department ID, employee count, and earliest hire date for each department_id value.
Assumptions:
- The
employeestable has one row per employee with adepartment_idand ahire_date. - Each
department_idvalue present inemployeesshould appear once in the result. - For each department, the employee count is the number of employees in that
department_id. The earliest hire date is the smallesthire_dateacross those employees.
Output:
- One row per department, with columns
department_id,employee_count, andearliest_hire.
Schema · hr 4 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
department_id,
COUNT(*) AS employee_count,
MIN(hire_date) AS earliest_hire
FROM
employees
GROUP BY
department_id The shape
Group employees by department_id, then count the rows and take the smallest hire date inside each group. The result is one row per department with the headcount and earliest hire already computed, which is the per-category summary worth caching in a temp table for the HR dashboard.
Clause by clause
SELECT department_id, COUNT(*) AS employee_count, MIN(hire_date) AS earliest_hirereturns three columns.department_idlabels each group;COUNT(*)counts the employees in that department (department 1 reports 17);MIN(hire_date)returns the smallest hire date among them, which is the earliest one.FROM employeesreads every employee record.GROUP BY department_idpartitions the rows by department so the aggregates run once per department. Without it,COUNT(*)would return one number for the whole company andMIN(hire_date)would return the single earliest hire across all of Helix.
Why MIN on a date
MIN and MAX work on any orderable type, not only on numbers. PostgreSQL knows how to compare two hire_date values, so MIN(hire_date) returns the earliest one in each group the same way MIN(salary) would return the lowest salary. "Earliest" and "smallest" are the same operation when the underlying type is a date.
You practiced a per-category aggregation that pairs a count with a MIN over a date — the kind of compact summary worth caching in a temp table for repeat use.