Employees with Falling Q1 2023 Net Pay

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

A payroll platform maintains employee records in employees and disbursement entries in payroll_transactions. Write a SQL query that identifies employees whose take-home pay decreased between their two latest pay periods in the first quarter of 2023 ('2023-01-01' through '2023-03-31').

Apply these payroll rules:

  • Q1 2023 scope: Include only transactions whose paid_at date falls between '2023-01-01' and '2023-03-31' inclusive. Ignore transactions outside Q1 2023 for both the quarterly total and the period-over-period comparison.
  • Net pay and same-day disbursements: Net pay on an entry equals gross_pay - deductions, treating NULL in deductions as 0. An employee's pay period corresponds to a distinct paid_at date: if an employee receives multiple transactions on the same paid_at date (for instance, regular wages and a bonus), sum their net pay into a single period total before comparing periods.
  • Eligibility and metrics:
    • q1_net_pay: sum of net pay across all Q1 2023 pay periods for that employee, rounded to 2 decimal places.
    • pct_change: percentage change from the employee's second-most-recent Q1 2023 pay period (prev_net) to their most-recent Q1 2023 pay period (latest_net), computed as 100.0 * (latest_net - prev_net) / prev_net and rounded to 4 decimal places (for example, -3.0 for a 3% drop).
    • Return only employees who have at least two Q1 2023 pay periods and satisfy latest_net < prev_net (exclude single-period employees, unchanged pay, and raises).

Return employee_id, q1_net_pay, and pct_change in any row order.

Input Schema

employees

Column Type Description
employee_id INTEGER Unique employee identifier
hire_date DATE Date the employee joined ('YYYY-MM-DD')
state VARCHAR Two-letter US work state code

payroll_transactions

Column Type Description
transaction_id INTEGER Unique disbursement record identifier
employee_id INTEGER Employee receiving the payment
paid_at DATE Payday date ('YYYY-MM-DD')
gross_pay DECIMAL(10,2) Pre-deduction earnings
deductions DECIMAL(10,2) Taxes and benefit withholdings (NULL when none apply)

Examples

Example 1

Input:

employees

employee_id hire_date state
11 2021-06-14 WA
12 2022-02-01 IL
13 2020-09-10 CO
14 2022-11-28 MA

payroll_transactions

transaction_id employee_id paid_at gross_pay deductions
10 11 2023-01-13 4200.00 400.00
11 11 2023-02-10 4400.00 400.00
12 11 2023-03-10 4400.00 520.00
13 12 2023-01-31 3600.00 300.00
14 12 2023-02-28 3600.00 350.00
15 13 2023-01-31 5000.00 500.00
16 13 2023-02-28 5200.00 500.00
17 14 2023-03-15 4800.00 450.00

Output:

employee_id q1_net_pay pct_change
11 11680.0 -3.0
12 6550.0 -1.5152

Explanation:

  • Employee 11 has three Q1 paydays (3800, 4000, 3880), totaling 11680.0. Comparing the latest two (4000 to 3880) gives 100 * (3880 - 4000) / 4000 = -3.0.
  • Employee 12 has two Q1 paydays (3300 then 3250), totaling 6550.0, with change 100 * (-50) / 3300 = -1.5152.
  • Employee 13's net pay rose (4500 to 4700), and employee 14 has only one Q1 payday, so both are excluded.

Example 2

Input:

employees

employee_id hire_date state
21 2021-03-01 OR
22 2021-08-15 GA

payroll_transactions

transaction_id employee_id paid_at gross_pay deductions
20 21 2023-01-20 3000.00 300.00
21 21 2023-01-20 600.00 NULL
22 21 2023-02-17 3300.00 330.00
23 22 2022-12-23 4000.00 400.00
24 22 2023-01-20 3500.00 400.00

Output:

employee_id q1_net_pay pct_change
21 6270.0 -10.0

Explanation:

Employee 21's two entries on '2023-01-20' (2700 plus 600 with NULL deductions treated as 0) form one 3300.0 pay period, followed by 2970.0 on '2023-02-17' (-10.0%, total 6270.0). Employee 22's December 2022 payment is outside Q1 2023, leaving only one Q1 pay period.

Constraints

  • transaction_id is unique across payroll_transactions; paid_at and gross_pay are non-NULL.
  • deductions may be NULL (meaning zero deductions).
  • Multiple rows may share the same (employee_id, paid_at) date and must be combined into one pay period.
  • If no employee qualifies, return zero rows.
  • Output row order does not matter.

Step-by-step walkthrough

  1. Restate the problem and define a pay period

    We are given payroll_transactions(transaction_id, employee_id, paid_at, gross_pay, deductions) (alongside employees, which we do not need to join because no column from employees appears in the output or filter). We must return one row per qualifying employee, in any order, with three columns:

    • employee_id: the employee's ID.
    • q1_net_pay: total Q1 2023 take-home pay (gross_pay - deductions) summed across payments dated 2023-01-01 through 2023-03-31, rounded to 2 decimal places.
    • pct_change: percentage change in net pay from the employee's second-most-recent Q1 2023 pay period to their most-recent Q1 2023 pay period, rounded to 4 decimal places (for example, -1.5152 for a 1.5152% decrease).

    Three rules keep edge cases unambiguous:

    1. Both metrics stay inside Q1 2023: Payments before 2023-01-01 or on/after 2023-04-01 are ignored for both q1_net_pay and the period-over-period comparison.
    2. A pay period is a pay date (paid_at), not a single row: An employee can receive two payments on the same day (such as regular wages plus a bonus, like employee 21 in Example 2). We must sum net pay per (employee_id, paid_at) before comparing periods.
    3. Strict decrease across at least two periods: Employees with only one Q1 pay period, unchanged pay, or a raise are excluded.
  2. Collapse Q1 transactions into one net-pay row per pay period

    First, we build a Common Table Expression (CTE — a named temporary result written with WITH) called period_net that filters to Q1 2023 and groups by (employee_id, paid_at):

    • Half-open date filter [2023-01-01, 2023-04-01): Writing paid_at >= '2023-01-01' AND paid_at < '2023-04-01' includes every date from January 1 through March 31 — even if paid_at ever carries a time component like '2023-03-31 17:00:00' (which BETWEEN '2023-01-01' AND '2023-03-31' would miss).
    • Safe NULL deductions with COALESCE(deductions, 0): In SQL, 600 - NULL evaluates to NULL, which would silently drop that payment from SUM. Wrapping deductions in COALESCE(..., 0) treats a missing deduction as 0.
    Same-day payments before grouping (Example 2, employee 21):
      (emp 21, 2023-01-20, gross=3000, ded=300)  --> net 2700 \
      (emp 21, 2023-01-20, gross=600,  ded=NULL) --> net  600 /  summed into ONE period: (21, 2023-01-20, 3300)
      (emp 21, 2023-02-17, gross=3300, ded=330)  -->             second period:          (21, 2023-02-17, 2970)
    
    -- Step 1: Collapse same-day Q1 2023 payments into one net-pay row per (employee_id, paid_at).
    -- Half-open range [2023-01-01, 2023-04-01) captures all of Q1, and COALESCE handles NULL deductions.
    WITH period_net AS (
        SELECT
            employee_id,
            paid_at,
            SUM(gross_pay - COALESCE(deductions, 0)) AS net_pay
        FROM payroll_transactions
        WHERE paid_at >= '2023-01-01'
          AND paid_at < '2023-04-01'
        GROUP BY employee_id, paid_at
    ),
    
  3. Attach the prior period, recency rank, and Q1 total with window functions

    Next, in with_previous, three window functions enrich every (employee_id, paid_at) row in a single pass without collapsing the periods:

    1. LAG(net_pay) OVER (PARTITION BY employee_id ORDER BY paid_at) AS previous_net looks back one period in chronological order for that employee. On the employee's very first Q1 period, previous_net is NULL.
    2. ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY paid_at DESC) AS recency numbers periods from newest to oldest (1 = most recent Q1 pay period, 2 = second-most-recent, and so on). Because period_net already has one row per (employee_id, paid_at), paid_at has no ties!
    3. SUM(net_pay) OVER (PARTITION BY employee_id) AS q1_net_pay adds up all Q1 periods for that employee (such as all 3 paydays for employee 11 in Example 1), because omitting ORDER BY inside OVER (...) sums the whole employee partition rather than a running total.
    -- Step 2: Attach the prior period's net pay, a latest-first rank, and the employee's full Q1 total.
    with_previous AS (
        SELECT
            employee_id,
            net_pay,
            LAG(net_pay) OVER (PARTITION BY employee_id ORDER BY paid_at) AS previous_net,
            ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY paid_at DESC) AS recency,
            SUM(net_pay) OVER (PARTITION BY employee_id) AS q1_net_pay
        FROM period_net
    )
    
  4. Filter to decreases and compute percentage change safely

    On the row where recency = 1, net_pay is the employee's most recent Q1 period and previous_net is their second-most-recent Q1 period:

    • WHERE recency = 1 AND net_pay < previous_net keeps only employees whose latest period dropped. If an employee had only one Q1 period (like employee 14), previous_net is NULL, net_pay < NULL evaluates to UNKNOWN (not TRUE), and the employee is automatically excluded!
    • 100.0 * (net_pay - previous_net) / NULLIF(previous_net, 0): Starting with 100.0 forces floating-point division (integer 100 * (3250 - 3300) / 3300 would truncate -1.5152 to -1!), and NULLIF(previous_net, 0) turns a 0 denominator into NULL so the query never crashes on division by zero.
    • ROUND(q1_net_pay, 2) and ROUND(..., 4) clean up any binary floating-point noise on cents and round pct_change to 4 decimal places.
    -- Step 3: Keep only each employee's latest Q1 period (recency = 1) when net pay strictly dropped.
    -- Multiply by 100.0 for floating-point division and guard against a zero denominator with NULLIF.
    SELECT
        employee_id,
        ROUND(q1_net_pay, 2) AS q1_net_pay,
        ROUND(100.0 * (net_pay - previous_net) / NULLIF(previous_net, 0), 4) AS pct_change
    FROM with_previous
    WHERE recency = 1
      AND net_pay < previous_net
    
  5. Trace Example 1 step by step

    Let's trace all 8 transactions from Example 1 through each stage:

    Stage 1 — period_net (all 8 rows are in Q1 2023, unique dates per employee):
    employee_id  paid_at     calculation    net_pay
    11           2023-01-13  4200 - 400     3800
    11           2023-02-10  4400 - 400     4000
    11           2023-03-10  4400 - 520     3880
    12           2023-01-31  3600 - 300     3300
    12           2023-02-28  3600 - 350     3250
    13           2023-01-31  5000 - 500     4500
    13           2023-02-28  5200 - 500     4700
    14           2023-03-15  4800 - 450     4350
    
    Stage 2 — with_previous (focusing on recency = 1 rows):
    employee_id  paid_at     net_pay  previous_net  recency  q1_net_pay  net_pay < previous_net?
    11           2023-03-10  3880     4000          1        11680       3880 < 4000 -> YES
    12           2023-02-28  3250     3300          1         6550       3250 < 3300 -> YES
    13           2023-02-28  4700     4500          1         9200       4700 < 4500 -> NO (dropped)
    14           2023-03-15  4350     NULL          1         4350       4350 < NULL -> UNKNOWN (dropped)
    
    Stage 3 — Final pct_change math:
      emp 11: 100.0 * (3880 - 4000) / 4000 = -12000.0 / 4000 = -3.0
      emp 12: 100.0 * (3250 - 3300) / 3300 =  -5000.0 / 3300 = -1.515151... -> -1.5152
    
  6. Complete query

    Combining both CTEs and the final SELECT gives the complete solution:

    -- Step 1: Collapse same-day Q1 2023 payments into one net-pay row per (employee_id, paid_at).
    -- Half-open range [2023-01-01, 2023-04-01) captures all of Q1, and COALESCE handles NULL deductions.
    WITH period_net AS (
        SELECT
            employee_id,
            paid_at,
            SUM(gross_pay - COALESCE(deductions, 0)) AS net_pay
        FROM payroll_transactions
        WHERE paid_at >= '2023-01-01'
          AND paid_at < '2023-04-01'
        GROUP BY employee_id, paid_at
    ),
    -- Step 2: Attach the prior period's net pay, a latest-first rank, and the employee's full Q1 total.
    with_previous AS (
        SELECT
            employee_id,
            net_pay,
            LAG(net_pay) OVER (PARTITION BY employee_id ORDER BY paid_at) AS previous_net,
            ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY paid_at DESC) AS recency,
            SUM(net_pay) OVER (PARTITION BY employee_id) AS q1_net_pay
        FROM period_net
    )
    -- Step 3: Keep only each employee's latest Q1 period (recency = 1) when net pay strictly dropped.
    -- Multiply by 100.0 for floating-point division and guard against a zero denominator with NULLIF.
    SELECT
        employee_id,
        ROUND(q1_net_pay, 2) AS q1_net_pay,
        ROUND(100.0 * (net_pay - previous_net) / NULLIF(previous_net, 0), 4) AS pct_change
    FROM with_previous
    WHERE recency = 1
      AND net_pay < previous_net
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture laying each employee's Q1 2023 pay stubs left to right on a table in date order — and if two checks arrived on the exact same date (say regular wages plus a bonus), stapling them together first so every payday has one combined take-home total. Once each payday is a single number, you add up every stub on the table for the employee's quarterly net pay, compare just the rightmost stub against the one immediately to its left, and keep the employee only if that final payday went down.

Two naive shortcuts commonly break here. First, applying window functions directly to raw payroll_transactions rows treats a smaller 600 same-day bonus check after a 2,700 regular check (like employee 21 in Example 2) as a separate "pay period", inventing a fake pay drop on the very same date! Second, comparing MIN(paid_at) against MAX(paid_at) compares the first and last paydays of Q1 rather than the two most recent paydays whenever an employee has three or more pay periods in the quarter (like employee 11 in Example 1, whose net pay went 3800 -> 4000 -> 3880, rising vs January yet dropping vs February).

Our query solves both cleanly with two Common Table Expressions (CTEs) — named temporary subqueries introduced with WITH — and three window functions (calculations across an employee's rows that attach prior values, rankings, or totals without collapsing rows). Take employee 11 from Example 1 with three Q1 paydays: Jan 13 -> 3800, Feb 10 -> 4000, and Mar 10 -> 3880:

  1. period_net filters to the half-open interval [2023-01-01, 2023-04-01) (inclusive of Jan 1, strictly before Apr 1), uses COALESCE(deductions, 0) (returns 0 whenever deductions is NULL), and sums by (employee_id, paid_at) to form the 3 period rows.
  2. with_previous uses LAG (fetches the value from the preceding row in date order), ROW_NUMBER (numbers periods 1, 2, 3 from latest date backward), and SUM(net_pay) OVER (PARTITION BY employee_id) (attaches the full Q1 sum 3800 + 4000 + 3880 = 11680 to every row).
  3. Filtering WHERE recency = 1 AND net_pay < previous_net isolates the Mar 10 row (net_pay = 3880, previous_net = 4000), uses NULLIF(previous_net, 0) (turns 0 into NULL to prevent division by zero), and computes 100.0 * (3880 - 4000) / 4000 = -3.0 alongside q1_net_pay = 11680.0.

Complexity

Let N be the total number of rows in payroll_transactions and Q be the number of rows dated in Q1 2023 (Q <= N).

  • Time: Filtering to Q1 scans N rows without an index, or O(log N + Q) rows using a B-tree index on paid_at. Grouping and sorting those Q rows by (employee_id, paid_at) for GROUP BY, LAG, and ROW_NUMBER takes O(Q log Q) time (or O(Q) streaming if an index already provides (employee_id, paid_at) order), followed by a single O(Q) pass to filter recency = 1.
  • Space: O(Q) working memory to hold the grouped Q1 (employee_id, paid_at, net_pay) rows during sorting and window evaluation.

Database indexes: A composite index on payroll_transactions(paid_at, employee_id) helps prune quickly when Q1 is a narrow slice of multi-year history, while payroll_transactions(employee_id, paid_at) (covering gross_pay, deductions) matches both GROUP BY employee_id, paid_at and the PARTITION BY employee_id ORDER BY paid_at window order directly.

Edge cases

  • Only one Q1 pay period: LAG produces previous_net = NULL on the recency = 1 row, net_pay < NULL evaluates to UNKNOWN, and the employee is excluded (such as employee 14 in Example 1 and employee 22 in Example 2).
  • Multiple transactions on the same paid_at date: Combined into a single pay period by GROUP BY employee_id, paid_at before any comparison runs (employee 21 in Example 2).
  • Three or more Q1 pay periods: Earlier periods still count toward q1_net_pay (via SUM(net_pay) OVER (PARTITION BY employee_id)), while recency = 1 compares strictly the last two periods (employee 11 in Example 1).
  • Transactions outside Q1 2023 (Dec 2022 or Apr 2023): Excluded in period_net, so they neither add to q1_net_pay nor act as a comparison period in LAG.
  • Flat pay (net_pay = previous_net) or a raise (net_pay > previous_net): Excluded by the strict inequality net_pay < previous_net (employee 13 in Example 1).
  • NULL deductions: Treated as 0 via COALESCE(deductions, 0) so gross_pay - deductions does not become NULL.
  • Zero or negative prior net pay: NULLIF(previous_net, 0) avoids division-by-zero errors; if payroll adjustments could ever make previous_net negative, dividing by ABS(previous_net) preserves the negative sign of a drop.
  • Empty payroll_transactions table: Returns zero rows cleanly with the expected column headers.

Common mistakes

  • Windowing raw rows instead of grouping by (employee_id, paid_at) first: Treats a same-day bonus or reimbursement row as a separate pay period and miscomputes pct_change.
  • Ordering by transaction_id instead of paid_at: Backfilled or corrected payroll records often have higher transaction_ids for earlier pay dates.
  • Comparing first and last Q1 periods (MIN vs MAX): Fails whenever an employee has 3 or more pay periods in Q1 (for example, employee 11 rose from Jan 13 to Mar 10 overall, yet fell from Feb 10 to Mar 10).
  • Applying the Q1 date filter after LAG: Allows a December 2022 paycheck to serve as previous_net for an employee paid only once in January 2023 (such as employee 22 in Example 2).
  • Integer division (100 * ... instead of 100.0 * ...): When gross_pay and deductions are integer values, 100 * (3250 - 3300) / 3300 truncates to -1 instead of -1.5152.
  • Filtering pct_change < 0 after ROUND(..., 4): A tiny drop smaller than 0.00005% rounds to 0.0000 and would be dropped if filtered post-rounding; always filter on net_pay < previous_net.

Follow-up questions

  • How could you express this query in a SQL engine that does not support window functions? After building period_net, find each employee's latest pay date MAX(paid_at) and SUM(net_pay) in one aggregate CTE, find their second-latest pay date with a second MAX(p.paid_at) where p.paid_at < latest.last_day, and join period_net twice to read the two net-pay amounts. This produces identical output in SQL dialects without window support, at the cost of self-joins instead of one sequential pass.
WITH period_net AS (
    SELECT
        employee_id,
        paid_at,
        SUM(gross_pay - COALESCE(deductions, 0)) AS net_pay
    FROM payroll_transactions
    WHERE paid_at >= '2023-01-01'
      AND paid_at < '2023-04-01'
    GROUP BY employee_id, paid_at
),
latest AS (
    SELECT
        employee_id,
        MAX(paid_at) AS last_day,
        SUM(net_pay) AS q1_net_pay
    FROM period_net
    GROUP BY employee_id
),
previous AS (
    SELECT
        p.employee_id,
        MAX(p.paid_at) AS prev_day
    FROM period_net AS p
    JOIN latest AS l
        ON l.employee_id = p.employee_id
       AND p.paid_at < l.last_day
    GROUP BY p.employee_id
)
SELECT
    l.employee_id,
    ROUND(l.q1_net_pay, 2) AS q1_net_pay,
    ROUND(100.0 * (cur.net_pay - prev.net_pay) / NULLIF(prev.net_pay, 0), 4) AS pct_change
FROM latest AS l
JOIN previous AS pv
    ON pv.employee_id = l.employee_id
JOIN period_net AS cur
    ON cur.employee_id = l.employee_id AND cur.paid_at = l.last_day
JOIN period_net AS prev
    ON prev.employee_id = l.employee_id AND prev.paid_at = pv.prev_day
WHERE cur.net_pay < prev.net_pay;
  • How would you break down each employee's net pay drop into gross-pay changes versus deduction changes? Carry SUM(gross_pay) and SUM(COALESCE(deductions, 0)) separately in period_pay and apply LAG to each component. Because net_change = gross_change - deductions_change, reporting both deltas side by side immediately separates wage reductions from benefit or tax withholding increases (in Example 1, both employees 11 and 12 had gross_change = 0 between their last two paydays while deductions rose by +120 and +50).
WITH period_pay AS (
    SELECT
        employee_id,
        paid_at,
        SUM(gross_pay) AS gross,
        SUM(COALESCE(deductions, 0)) AS deductions
    FROM payroll_transactions
    WHERE paid_at >= '2023-01-01'
      AND paid_at < '2023-04-01'
    GROUP BY employee_id, paid_at
),
with_previous AS (
    SELECT
        employee_id,
        gross,
        deductions,
        LAG(gross) OVER (PARTITION BY employee_id ORDER BY paid_at) AS prev_gross,
        LAG(deductions) OVER (PARTITION BY employee_id ORDER BY paid_at) AS prev_deductions,
        ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY paid_at DESC) AS recency
    FROM period_pay
)
SELECT
    employee_id,
    gross - prev_gross AS gross_change,
    deductions - prev_deductions AS deductions_change,
    (gross - deductions) - (prev_gross - prev_deductions) AS net_change
FROM with_previous
WHERE recency = 1
  AND (gross - deductions) < (prev_gross - prev_deductions);
  • How would you adapt the query if an employee with a single Q1 2023 paycheck should be compared against their final 2022 paycheck while keeping q1_net_pay restricted to Q1? Keep all historical periods with paid_at < '2023-04-01' in period_net so LAG can reach back into 2022 (which would bring employee 22 from Example 2 into comparison against '2022-12-23'), compute q1_net_pay with a conditional window sum SUM(CASE WHEN paid_at >= '2023-01-01' THEN net_pay ELSE 0 END) OVER (PARTITION BY employee_id), and add AND paid_at >= '2023-01-01' in the outer WHERE so the latest paycheck itself occurred in Q1 2023.
WITH period_net AS (
    SELECT
        employee_id,
        paid_at,
        SUM(gross_pay - COALESCE(deductions, 0)) AS net_pay
    FROM payroll_transactions
    WHERE paid_at < '2023-04-01'
    GROUP BY employee_id, paid_at
),
with_previous AS (
    SELECT
        employee_id,
        paid_at,
        net_pay,
        LAG(net_pay) OVER (PARTITION BY employee_id ORDER BY paid_at) AS previous_net,
        ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY paid_at DESC) AS recency,
        SUM(CASE WHEN paid_at >= '2023-01-01' THEN net_pay ELSE 0 END)
            OVER (PARTITION BY employee_id) AS q1_net_pay
    FROM period_net
)
SELECT
    employee_id,
    ROUND(q1_net_pay, 2) AS q1_net_pay,
    ROUND(100.0 * (net_pay - previous_net) / NULLIF(previous_net, 0), 4) AS pct_change
FROM with_previous
WHERE recency = 1
  AND paid_at >= '2023-01-01'
  AND net_pay < previous_net;

Follow-up questions

Similar questions

More Gusto interview questions

All 15 Gusto questions →