Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A nightly job finds accounts with no activity in 2 years using LEFT JOIN activity ... WHERE activity.id IS NULL over 300 million activity rows, and it now runs for 4 hours. How would you make it fast and safe?

Rewrite the job as NOT EXISTS against an index on activity(account_id, occurred_at), with the two-year cutoff inside the subquery, so each account costs one short index probe that stops at the first recent row instead of a join over 300 million rows. Better still, keep a last_activity_at column on accounts, updated when activity is written, so the job becomes a simple indexed filter. Run it in key-range batches with short transactions, on a replica if it only reads, and confirm each change with EXPLAIN ANALYZE before and after.

Why this question is asked

Batch jobs that find what did not happen, accounts with no logins, customers with no orders, devices with no heartbeat, are common and tend to get slower every month, because the history table only grows. A four-hour run is not just slow; it holds a long transaction, delays vacuum, lags replicas and eventually overlaps the next run. Interviewers use this scenario to see whether we can fix the query, but also whether we can change the design so the problem stops growing. In this answer, we will understand why the current query is slow, rewrite it as an anti-join with the right index, then remove the scan altogether with a denormalised column, and finally make the job safe to run.

1Why the Current Query Takes Four Hours

The job probably looks like the query below. It left joins every account to its recent activity and keeps the accounts where nothing matched, the IS NULL test on a column that cannot be NULL in a real activity row.

SQL
SELECT acc.id
FROM accounts acc
LEFT JOIN activity a
ON a.account_id = acc.id
AND a.occurred_at > now() - interval '2 years'
WHERE a.id IS NULL;

The logic is fine, but think about what the database may do with it. If the planner does not recognise it as an anti-join, or has no suitable index, it joins every account to all of its recent activity rows, possibly hundreds per account, only to discard them because we only care about accounts with none. If someone moved the date condition from ON into WHERE at some point, it would be worse: the time filter would then remove the matched rows after the join and return wrong results. With 300 million activity rows, a hash join that builds on activity needs a huge hash table, spills to disk in many batches, and runs for hours. The size of the history drives the cost, even though the answer only depends on one fact per account: the date of its latest activity.

2Fix 1: NOT EXISTS on the Right Index

The first step is to express the question directly: accounts for which no activity exists after the cutoff. With a composite index whose first column is account_id and second is occurred_at, each check becomes a single descent of the index to the first entry for that account after the cutoff.

Java
CREATE INDEX CONCURRENTLY activity_account_time_idx ON activity (account_id, occurred_at);
SELECT acc.id
FROM accounts acc
WHERE NOT EXISTS (
SELECT 1 FROM activity a
WHERE a.account_id = acc.id
AND a.occurred_at > now() - interval '2 years'
);
-- Nested Loop Anti Join
-- -> Seq Scan on accounts acc (rows=2000000)
-- -> Index Only Scan using activity_account_time_idx on activity a
-- Index Cond: ((account_id = acc.id) AND (occurred_at > ...)) (loops=2000000, at most 1 row read each)
Where the work goes
ApproachWork per runGrows with
LEFT JOIN over all activityJoin hundreds of rows per account, then discardActivity history (300M rows)
NOT EXISTS + (account_id, occurred_at)One index probe per accountNumber of accounts (2M)
last_activity_at column + indexRead only the inactive accountsNumber of results

Notice what changed. For an active account, the probe finds a recent entry immediately and stops. For an inactive one, it finds nothing after the cutoff, which also takes only a few page reads. The cost now depends on the number of accounts, say 2 million probes, not on the 300 million activity rows. CREATE INDEX CONCURRENTLY builds the index without blocking writes, at the price of a slower build, which matters on a busy table. In practice this kind of change takes a job from hours to minutes, but we should measure rather than promise.

3Fix 2: Keep last_activity_at on the Account

The deeper fix is to store the one fact the job needs. If accounts has a last_activity_at column that the application updates when it records activity, the nightly job becomes a filter on one indexed column, and it no longer touches the activity table at all.

SQL
ALTER TABLE accounts ADD COLUMN last_activity_at timestamptz;
-- On every write of activity, done in the same transaction:
UPDATE accounts
SET last_activity_at = $2
WHERE id = $1
AND (last_activity_at IS NULL OR last_activity_at < $2 - interval '1 day'); -- at most one update per day
CREATE INDEX CONCURRENTLY accounts_last_activity_idx ON accounts (last_activity_at);
SELECT id FROM accounts WHERE last_activity_at < now() - interval '2 years'; -- index range scan

Notice the extra condition in the update. A busy account may produce activity every second, and updating the same accounts row each time would create a hot row and a lot of dead tuples. Since the job only needs day precision, we update at most once a day per account, which cuts the write cost to almost nothing. We backfill the column once from the activity table, in batches, and then compare its results with the NOT EXISTS query for a few nights before switching the job over. The trade-off is that the column is now part of the write path, so every code path that writes activity must update it; a trigger is an option if not all writers go through the service.

4Making the Job Safe to Run

Even a fast query should not run as one huge transaction. A transaction open for an hour holds back vacuum on every table, lets bloat build up, and on a primary with replicas it can cause lag. So the job walks the accounts in key ranges, for example 10,000 ids at a time, and commits after each batch. It remembers the last id it finished, so a failure resumes where it stopped instead of starting again.

SQL
-- Keyset batches: each statement is short and uses the primary key
SELECT id FROM accounts
WHERE id > :last_id
AND last_activity_at < now() - interval '2 years'
ORDER BY id
LIMIT 10000;
-- process the batch (flag, notify, archive), commit, store the last id, repeat
Step throughThe nightly job after the change
  1. Read the last processed idstored by the previous run
  2. Select the next 10,000 inactive accountsindexed filter, keyset order
  3. Any rows?
    YesProcess them and commitNoFinish and record the run
  4. Store the last id of the batchresume point after a failure

4 steps in order. Play them, or step through them one at a time.

If the job only reads and reports, it can run on a read replica so the primary carries none of its load. There is a catch: on a PostgreSQL hot standby, a long query can be cancelled when replication needs to remove rows it is reading, depending on max_standby_streaming_delay, and hot_standby_feedback avoids that by holding back vacuum on the primary. Short batches avoid both problems. If the job then flags or deletes accounts, the writes go to the primary in small batches too, ideally throttled so replicas keep up.

Finally, we prove each step. We capture EXPLAIN (ANALYZE, BUFFERS) for the old query, the NOT EXISTS version and the column version on production-sized data, and compare total time and buffers read. That record also helps the next person who wonders why the column exists.

5Follow-up questions

Would partitioning the activity table by month help?

It helps the history table in general: old partitions can be dropped or archived cheaply and queries with a date range skip partitions they do not need. For this job, partition pruning means the NOT EXISTS probe only looks at partitions newer than the cutoff, which shrinks the indexes it uses. But it does not replace the last_activity_at idea, which removes the need to look at activity at all.

How do you make sure last_activity_at never drifts from the real data?

We write it in the same transaction as the activity, so both commit or neither does. For writers outside the service, a trigger on the activity table can do the same update. And a weekly check compares a sample of accounts with the maximum occurred_at in activity and reports any difference, which catches a missing code path early.

Why not run the job on the primary at night when traffic is low?

We can, and with short batches it is usually fine. The risk is that night is when other maintenance runs too, backups, vacuum and other batch jobs, and traffic in another time zone may not be low. A replica isolates a read-only job completely, and batching keeps the primary safe if we cannot use one.

6Conclusion

In this answer, we saw that the LEFT JOIN ... IS NULL job scales with the 300 million activity rows, rewrote it as NOT EXISTS on an index of activity(account_id, occurred_at) so each account costs one short probe, and then removed the scan entirely with a last_activity_at column updated at most once a day per account. We ran the job in keyset batches with short transactions, on a replica when it only reads, and verified every change with EXPLAIN ANALYZE.

What to say in the interviewAbout 100 seconds aloud

Open with

The job is slow because its cost follows the activity table, 300 million rows and growing, while the answer only depends on one fact per account, its latest activity.

Then, if they want more

The LEFT JOIN with IS NULL may join each account to all its recent activity just to throw it away, and a hash join on that much data spills to disk for hours.

My first fix is to write it as NOT EXISTS, with the two-year cutoff inside the subquery, and add a composite index on activity account_id, occurred_at, built concurrently. Then each account is one short index probe that stops at the first recent entry, so the work is proportional to accounts, a couple of million probes, not to activity.

The second, better fix is a last_activity_at column on accounts, updated in the same transaction as the activity, but only when the stored value is more than a day old, so busy accounts do not become hot rows.

Backfill it in batches, compare with the NOT EXISTS result for a few nights, then the job is just an indexed filter on that column. To make it safe, I run it in keyset batches of around 10,000 ids, commit after each, and store the last id so it can resume.

If it only reads, it runs on a replica, keeping batches short to avoid standby query cancellations. And I would capture EXPLAIN ANALYZE with buffers before and after each change to prove it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A nightly job finds accounts with no activity in 2 years using LEFT JOIN activity ......": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/9f2cff2976/