// SQL snippet

Find rows changed since yesterday

Filter on the row's updated_at timestamp against a 24-hour window and sort newest first for a change feed.

Main statement
PostgreSQL
Deckt außerdem ab
SQL Server MySQL

The task

Something rewrote a pile of customers overnight. The updated_at column tells you which rows moved and when, if the app maintains it on every write.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT id, email, name, updated_at,
       updated_at::date AS change_day
FROM customers
WHERE updated_at >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
ORDER BY updated_at DESC;

So funktioniert es

The predicate compares updated_at against now minus 24 hours, so the window rolls with the clock instead of being fixed to calendar days. Ordering by updated_at DESC reads the result as a change feed. The ::date cast buckets rows by day for a quick before/after picture.

Variations

MySQL: NOW() arithmetic

MySQL
SELECT id, email, name, updated_at
FROM customers
WHERE updated_at >= NOW() - INTERVAL 24 HOUR
ORDER BY updated_at DESC;

SQL Server: DATEADD

SQL Server
SELECT id, email, name, updated_at
FROM customers
WHERE updated_at >= DATEADD(HOUR, -24, SYSDATETIME())
ORDER BY updated_at DESC;

Questions that come up

What if updated_at is not maintained?

Then the query silently under-reports: rows changed by paths that skip the column look untouched. Check that every write path (app code, bulk updates, triggers) sets the timestamp, or let the database maintain it: ON UPDATE CURRENT_TIMESTAMP on a MySQL column, a BEFORE UPDATE trigger on PostgreSQL and Oracle, and an AFTER UPDATE trigger that updates the row again on SQL Server and SQLite, which cannot change NEW values in a trigger.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.