Pairing Clock-In and Clock-Out Records Across Calendar Days
SQL & DataModel answerLast updated
Calculate daily hours worked per employee from timestamp-based clock events, handling midnight transitions and data anomalies.
You maintain a time-tracking system that records when employees clock in and out. Your task is to calculate how many hours each employee worked on each calendar day.
You have a table of clock events:
events(employee_id INT, evt_ts TIMESTAMP, action VARCHAR)
where action is either 'in' or 'out'.
Example data:
employee_id | evt_ts | action
------------|---------------------|-------
101 | 2025-01-30 08:00:00 | in
101 | 2025-01-30 13:00:00 | out
101 | 2025-01-30 14:00:00 | in
101 | 2025-01-30 18:30:00 | out
102 | 2025-01-30 22:00:00 | in
102 | 2025-01-31 06:00:00 | out
103 | 2025-01-30 09:00:00 | in
103 | 2025-01-30 12:00:00 | out
103 | 2025-01-30 12:30:00 | out
Your solution must:
- Match each clock-in with its corresponding clock-out (the next
'out'event chronologically for that employee) - Handle shifts that cross midnight by attributing hours to the correct calendar days
- Deal with incomplete or malformed data:
- If a clock-in has no matching clock-out, count hours until 23:59:59 of that same day
- Ignore clock-out events that have no preceding clock-in
- Round daily totals to the nearest quarter-hour (0.25)
- Mark days where anomalies occur (consecutive clock-ins, consecutive clock-outs, or duplicate timestamps)
Return a result set with columns:
employee_idwork_date(the calendar date)hours_worked(rounded to nearest 0.25)dq_issue_flag(boolean indicating data quality problems on that day)
Write a SQL query (PostgreSQL dialect) to produce this output.
Hints
Hint 1
Use window functions like LEAD and LAG to examine adjacent events for each employee without expensive self-joins
Hint 2
When a shift spans multiple days, generate one row per affected calendar day and clip the time interval to that day's boundaries
Hint 3
Round the summed daily total rather than rounding individual segments to avoid compounding rounding errors
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Pairing Clock Events and Computing Daily Hours
Approach
This problem requires careful sequencing of operations:
- Order events and identify neighbors using window functions
- Construct work intervals by pairing clock-ins with their next clock-out
- Split intervals across calendar boundaries when shifts cross midnight
- Aggregate and round hours per employee per day
- Detect anomalies and flag problematic days
The core challenge is handling real-world messiness: missing clock-outs, duplicate events, and shifts that span multiple calendar days.
SQL Solution
WITH ordered AS (
-- Add context: what came before and after each event
SELECT
employee_id,
evt_ts,
action,
LAG(action) OVER w AS prev_action,
LEAD(action) OVER w AS next_action,
LEAD(evt_ts) OVER w AS next_ts
FROM events
WINDOW w AS (PARTITION BY employee_id ORDER BY evt_ts, action)
),
work_intervals AS (
-- Build intervals from consecutive in->out pairs
SELECT
employee_id,
evt_ts AS start_ts,
CASE
WHEN next_action = 'out' THEN next_ts
WHEN next_action IS NULL THEN
DATE_TRUNC('day', evt_ts) + INTERVAL '1 day' - INTERVAL '1 second'
ELSE NULL -- in->in case: skip this clock-in
END AS end_ts
FROM ordered
WHERE action = 'in'
),
day_segments AS (
-- Split each interval into daily pieces
SELECT
wi.employee_id,
d::date AS work_date,
EXTRACT(EPOCH FROM (
LEAST(wi.end_ts, d + INTERVAL '1 day') -
GREATEST(wi.start_ts, d)
)) / 3600.0 AS segment_hours
FROM work_intervals wi
CROSS JOIN LATERAL GENERATE_SERIES(
DATE_TRUNC('day', wi.start_ts),
DATE_TRUNC('day', wi.end_ts),
INTERVAL '1 day'
) AS d
WHERE wi.end_ts IS NOT NULL
AND LEAST(wi.end_ts, d + INTERVAL '1 day') > GREATEST(wi.start_ts, d)
),
daily_totals AS (
SELECT
employee_id,
work_date,
SUM(segment_hours) AS total_hours
FROM day_segments
GROUP BY employee_id, work_date
),
anomalies AS (
-- Find days with data quality issues
SELECT DISTINCT
employee_id,
evt_ts::date AS work_date
FROM ordered
WHERE (action = 'in' AND next_action = 'in') -- consecutive clock-ins
OR (action = 'out' AND prev_action IS DISTINCT FROM 'in') -- orphan clock-out
OR EXISTS (
SELECT 1 FROM events e2
WHERE e2.employee_id = ordered.employee_id
AND e2.evt_ts = ordered.evt_ts
AND e2.action != ordered.action
) -- duplicate timestamp with different action
)
SELECT
COALESCE(dt.employee_id, a.employee_id) AS employee_id,
COALESCE(dt.work_date, a.work_date) AS work_date,
ROUND(COALESCE(dt.total_hours, 0) * 4) / 4.0 AS hours_worked,
(a.employee_id IS NOT NULL) AS dq_issue_flag
FROM daily_totals dt
FULL OUTER JOIN anomalies a
ON dt.employee_id = a.employee_id
AND dt.work_date = a.work_date
ORDER BY employee_id, work_date;
How It Works
Step 1: Ordering and context
Window functions partition events by employee and sort chronologically. LAG and LEAD let each row see its neighboring events without expensive self-joins. Sorting by (evt_ts, action) ensures deterministic ordering when timestamps tie (clock-in sorts before clock-out alphabetically).
Step 2: Building work intervals
Only clock-in events start intervals. Each looks at its next_action:
- If next is
'out': normal pair, usenext_tsas end - If next is
NULL: final event of the day, cap at 23:59:59 - If next is
'in': data error (consecutive clock-ins), skip this start
This logic ensures no interval double-counts time and every clock-out is used at most once.
Step 3: Splitting across midnight
GENERATE_SERIES produces one row per calendar day touched by the interval. For each day d, we compute the intersection of the work interval with [d, d+1) using GREATEST for the start and LEAST for the end. This naturally handles shifts spanning multiple days and ensures the pieces sum to the original duration.
Step 4: Aggregation and rounding
Sum all segments per (employee_id, work_date), then round to the nearest 0.25 hours using ROUND(hours * 4) / 4. Rounding the total rather than individual segments avoids compounding errors.
Step 5: Anomaly detection
Flag days where:
- Consecutive clock-ins occur (means an interval was skipped)
- A clock-out has no preceding clock-in (orphan event)
- Duplicate timestamps exist with conflicting actions
The FULL OUTER JOIN ensures days with anomalies but zero hours still appear in the output.
Example Walkthrough
For employee 101:
- 08:00–13:00 = 5 hours
- 14:00–18:30 = 4.5 hours
- Total: 9.5 hours on 2025-01-30, no anomalies
For employee 102:
- 22:00–23:59:59 = 2 hours on 2025-01-30
- 00:00–06:00 = 6 hours on 2025-01-31
- Total: 8 hours across two days, no anomalies
For employee 103:
- 09:00–12:00 = 3 hours
- 12:30 clock-out is orphaned (previous event was clock-out at 12:00)
- Total: 3 hours on 2025-01-30, flagged for anomaly
Complexity
Time: O(N log N) per employee for the window sort, where N is total events. The midnight expansion adds O(S × D) where S is sessions and D is days per session (typically 1–2). Overall: O(N log N).
Space: O(N) for intermediate CTEs and the sorted partitions.
Indexing: An index on (employee_id, evt_ts) improves window function performance at scale.
Edge Cases and Trade-offs
Policy decision: When you see in, in, out, which clock-in should pair with the clock-out? This solution pairs the second clock-in (the one adjacent to the clock-out), treating the first as an error. The alternative—pairing the first clock-in—would require tracking unpaired starts across multiple events, increasing complexity. State your choice explicitly in an interview.
Timezone handling: The solution assumes timestamps are already in the correct local timezone. If timestamps are UTC, convert using AT TIME ZONE before extracting dates, or daily boundaries will be wrong.
Long shifts: A shift lasting more than 24 hours is handled correctly but might indicate data errors. Consider adding a validation rule (e.g., max 16-hour shifts).
Tied timestamps: The ORDER BY evt_ts, action clause handles ties deterministically. Two events at the same instant with different actions will be ordered alphabetically, making clock-in come before clock-out.
Rounding: PostgreSQL's ROUND function uses "round half away from zero" behavior. If payroll requires banker's rounding (round half to even), adjust accordingly.
Leading clock-out: If an employee's first-ever event is a clock-out, it has no preceding clock-in (prev_action IS NULL), so it's correctly identified as an orphan and flagged.
What Interviewers Want to See
- Window functions over self-joins for cleaner, more efficient neighbor access
- Explicit handling of malformed data with a clear pairing policy stated upfront
- Correct midnight logic that attributes hours to the right calendar days
- Rounding only after aggregation to avoid compounding errors
- Full outer join to ensure anomaly-only days still appear in output
- Discussion of real-world considerations like timezones, duplicate events, and validation thresholds