Agents hired before their manager
Some agents have been at the help desk longer than the person they report to. HR wants the list.
In agents, manager_id points at another row in the same table. Managers themselves have a NULL
manager_id and should not appear in the output.
An agent counts if their hired_date is strictly earlier than their manager’s. Hired on the same
day doesn’t count.
Return one row per such agent:
| column | type | meaning |
|---|---|---|
agent_id |
integer | the agent |
agent_name |
text | the agent’s name |
manager_name |
text | their manager’s name |
Row order doesn’t matter.
Tables: agents.
helpdesk
A support desk. Synthetic data, generated by scripts/gen-datasets.mjs.
Click a table to preview its first 10 rows.
agents 20 rows
20 agents in 3 teams. Agents 1–3 are managers (manager_id NULL); everyone else reports to one of them.
tickets 800 rows
800 tickets from 2025-01-01. About 8% are still open (closed_at NULL).
ticket_events 2,779 rows
opened, first_response, reassigned, customer_reply, closed.
slas 4 rows
response and resolve targets in hours, per priority.
Hints get more specific as you go. Reveal one, try again, then come back.
The agent and the manager are both rows in agents. Join the table to itself, with two different
aliases.
FROM agents a JOIN agents m ON m.agent_id = a.manager_id. Now a is the agent and m is their
manager, side by side in one row.
An inner join already drops managers (their manager_id is NULL, so it matches nothing). Then keep
a.hired_date < m.hired_date.
Try one more hint first? The solution is always here, but working it out is what makes it stick.
Approach
Self-join: give agents two aliases, one for the agent and one for the manager, and compare their
hire dates.
SELECT a.agent_id,
a.name AS agent_name,
m.name AS manager_name
FROM agents a
JOIN agents m ON m.agent_id = a.manager_id
WHERE a.hired_date < m.hired_date;
Why it works
A join doesn’t care that both sides are the same table. The aliases make two independent row
streams, and the ON clause pairs each agent with exactly one manager row.
Managers drop out on their own: NULL = anything is never true, so an inner join finds no partner
for them. < rather than <= leaves out agents hired on the same day as their manager.
Under the hood
DuckDB reads agents twice, once per alias. It builds a hash table on m.agent_id (the primary key,
so one row per key) and probes it with each agent’s manager_id. Rows with a NULL key skip the probe
entirely. With 20 rows it all fits in a cache line or two; the same plan works for 20 million.
Per-problem discussion threads are coming. Until then, questions and better solutions are welcome on LinkedIn or by email at hello@builtfrombits.com.
Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.