# One DATE() call was locking 1.4 million rows every five minutes

> How a function call in a WHERE clause and InnoDB's locking reads in INSERT ... SELECT turned a five-minute cron into a table-wide lock, and the two-line fix.

Source: https://ebrahimsameh.com/blog/date-call-locked-rows/
Updated: 2026-11-25

A cron job that summed up today's sales was locking every row in a 1.4-million-row table every five minutes. The query wrapped an indexed column in `DATE()`, so MySQL scanned the whole table, and it ran as an `INSERT ... SELECT`, so InnoDB took a shared lock on every row it read. Rewriting the filter as a plain date range and running the statement at READ COMMITTED fixed it. The same pattern then fixed two more lock problems on the same database.

This was on a client's multi-tenant gift-card and voucher platform, a PHP app on MySQL 8.

## What broke

Two writes failed with `1205 Lock wait timeout exceeded`, three seconds apart. One was a partner extending a voucher's validity. The other was a payment callback marking a card as paid. Both were single-row `UPDATE`s on unrelated rows, for two different companies, one record from 2024 and one created minutes earlier. Neither statement held any other locks, so neither was the blocker. Something else was holding locks on rows across the whole table.

The database's `BlockedTransactions` metric spiked for exactly that minute and was flat zero before and after. The `Deadlocks` metric stayed at zero. So this was a plain lock wait: a long-running statement held locks, and the two updates waited the full 50-second `innodb_lock_wait_timeout` and died.

## How I found the blocker

Slowly. It took about 50 minutes, mostly because production kept no historical record of SQL. The slow query log was off, `performance_schema` was off, and so was the managed database's query insights feature. I had to work it out from timestamps.

I went through every scheduled job near the time of the errors and ruled them out one by one: one had finished twelve minutes earlier, one had last run more than 40 minutes before, one reported 0.3 seconds of runtime. The one left was a job that rebuilt today's sales totals, scheduled every five minutes:

```sql
INSERT INTO sums (...)
SELECT ... FROM gift_card
LEFT JOIN item_data ON item_data.id = gift_card.item_data
WHERE DATE(gift_card.created_at) = CURDATE()
```

That looks harmless. It reads today's rows and writes a summary.

## Root cause: three facts that compose

1. `DATE(created_at)` is not sargable. MySQL can't use the index on `created_at` when the column is inside a function call, so it evaluates the function on every row.
2. Under REPEATABLE READ, the default isolation level in InnoDB, an `INSERT ... SELECT` takes shared next-key locks on every source row it reads. A plain `SELECT` reads a snapshot and locks nothing, but the `SELECT` half of an `INSERT ... SELECT` is a locking read.
3. The `LEFT JOIN` probes `item_data` by primary key and locks those rows too.

Put together, every five minutes the statement shared-locked every gift card in the table, for every company and every year, plus their joined rows. A writer that landed on any of those rows queued behind it.

`EXPLAIN` on production showed it clearly:

| Filter | Access type | Key | Rows examined |
| --- | --- | --- | --- |
| `DATE(created_at) = CURDATE()` | ALL (full scan) | none | 1,384,845 |
| half-open range | range | `created_at` | 293 |

Only 293 cards had been created that day. The job read 4,727 times more rows than it needed and locked all of them.

## The fix

Two changes, and both were needed.

First, make the filter sargable with a half-open range:

```sql
WHERE gift_card.created_at >= CURDATE()
  AND gift_card.created_at <  CURDATE() + INTERVAL 1 DAY
```

It returns the same rows. Both forms evaluate `CURDATE()` in the same session time zone, and the column is written by SQL `NOW()`, so there's no edge case at midnight.

Second, run the statement at READ COMMITTED. At that level, the source side of an `INSERT ... SELECT` becomes a consistent read that takes no row locks. Only the rows written into the destination table are locked.

```php
$previous = $db->createCommand('SELECT @@SESSION.transaction_isolation')->queryScalar();
$db->createCommand('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED')->execute();
try {
    $db->createCommand($sql)->execute();
} finally {
    // SET takes no placeholders, so map $previous through a whitelist first
    $db->createCommand('SET SESSION TRANSACTION ISOLATION LEVEL ' . $whitelist[$previous])->execute();
}
```

The restore matters. The same summary class also had a full rebuild that ran at the end of every CSV import in the admin panel, inside a web request, where the connection lives on after the call. That full rebuild has no date filter at all, so it can't be made sargable. Isolation level was the only lever for it, and it could run under live traffic at any hour.

Before switching, I checked that it was safe. MySQL restricts READ COMMITTED when binary logging is statement-based, but binary logging was off on this cluster and the format was ROW, so that restriction didn't apply.

The new unit test was checked against the old predicate first. It failed on the `DATE()` version and passed on the range, so it guards against someone writing the function call back in later.

## The same pattern, twice more

Once I knew what to look for, it showed up elsewhere.

First, a search-index sync deadlocked with web requests. Another five-minute job staged its work queue with `INSERT INTO <temp table> SELECT id FROM ... WHERE flag = 'PREPARE'`. Under REPEATABLE READ that scan took shared locks on every flagged row, while web requests were flipping rows to `PREPARE` with exclusive locks. The two deadlocked (`1213`). The fix ran that one statement at READ COMMITTED and left the others alone. The destination was a session-local temporary table, so nothing else could see what the snapshot read wrote.

Second, a finance export blocked point-of-sale claims for about three minutes. An admin ran a bookkeeping export across all companies. It was one `INSERT INTO export ... SELECT` that joined cards, status history and payments, and it ran for 174 seconds. During that window, a full claim from a point-of-sale terminal waited 50 seconds and failed with `1205`. The terminal got an HTTP 500 and didn't retry, so the claim was never recorded. A payment callback failed the same way 36 seconds later. When I lined up every `1205` in production since the start of August against the request log, every one of them fell inside one of these exports, each running 127 seconds or more. Moving that statement to READ COMMITTED removed the lock holder behind all of them.

There was a fourth, smaller one: a cleanup `DELETE` on that export table used `NOW() > DATE_ADD(insertDate, INTERVAL 1 DAY)`. Same mistake, different function. Rewritten as `insertDate < DATE_SUB(NOW(), INTERVAL 1 DAY)`, it range-scans the index and only locks the expired rows.

## What changes at READ COMMITTED

The trade-off is small but real. The statement now reads one snapshot taken when it starts. Rows committed while it runs are left out, where before they might have been included. For a summary that rebuilds every five minutes, or an export of history, that's fine. For something that has to see the latest committed state, it might not be.

## What to check in your own system

- Search for `INSERT ... SELECT`, `CREATE TABLE ... SELECT` and `UPDATE ... JOIN` statements that run on a schedule or under live traffic. Under REPEATABLE READ, all of them lock what they read.
- Look for indexed columns wrapped in functions inside `WHERE`: `DATE(col)`, `YEAR(col)`, `DATE_ADD(col, ...)`, `LOWER(col)`. Move the function to the constant side.
- Run `EXPLAIN` on the real statement. If you see `type: ALL` on a big table in a statement that writes, you're locking that whole table.
- Turn on the slow query log before you need it. `slow_query_log` and `long_query_time` are dynamic, so you don't need a restart, and they would have named this statement in minutes instead of 50.

The original fix needed both halves. The range filter cut the rows read from 1.4 million to 293, and READ COMMITTED meant those 293 weren't locked either. A related story about scheduled jobs running on more than one server is in [Your "singleton" cron runs on every server](/blog/singleton-cron-runs-everywhere/).
