// SQL snippet

Report on last-modified staleness

Group rows into freshness buckets built from updated_at and created_at to see how stale a table is overall.

Main statement
PostgreSQL
Couvre également
MySQL

The task

A CRM table where most rows have not moved in years is a candidate for archiving, and stale updated_at values also hint at dead imports. One query buckets the whole table by freshness.

The snippet

Written for PostgreSQL. Versions for MySQL are under Variations.

PostgreSQL
SELECT CASE
         WHEN updated_at IS NULL THEN 'never tracked'
         WHEN updated_at = created_at THEN 'never updated'
         WHEN updated_at < CURRENT_TIMESTAMP - INTERVAL '1 year' THEN 'over a year'
         WHEN updated_at < CURRENT_TIMESTAMP - INTERVAL '90 days' THEN '90+ days'
         ELSE 'recent'
       END AS freshness,
       COUNT(*) AS row_count
FROM customers
GROUP BY 1
ORDER BY row_count DESC;

Fonctionnement

The CASE expression maps each row to a freshness label, evaluated top to bottom: never-tracked and never-updated are caught first, then the aging thresholds. The IS NULL branch has to come first, because a NULL updated_at fails every comparison and would otherwise fall through to 'recent'. GROUP BY 1 groups by the first select-list column, which PostgreSQL, MySQL and SQLite allow. Rows marked 'never updated' still equal their creation timestamp, a soft signal that the row was written once and left alone.

Variations

Stalest rows within a slice

SELECT id, email, updated_at
FROM customers
WHERE updated_at IS NOT NULL
  AND updated_at < CURRENT_TIMESTAMP - INTERVAL '1 year'
ORDER BY updated_at
LIMIT 100;

MySQL version

MySQL
SELECT CASE
         WHEN updated_at IS NULL THEN 'never tracked'
         WHEN updated_at = created_at THEN 'never updated'
         WHEN updated_at < NOW() - INTERVAL 1 YEAR THEN 'over a year'
         WHEN updated_at < NOW() - INTERVAL 90 DAY THEN '90+ days'
         ELSE 'recent'
       END AS freshness,
       COUNT(*) AS row_count
FROM customers
GROUP BY 1
ORDER BY row_count DESC;

Questions that come up

Is 'never updated' bad?

Not on its own. Reference data and stable customers legitimately never change. It becomes a data-quality signal when the share is large and unexpected, or when the rows also look wrong (missing fields, old formats). Pair the bucket counts with the row lists to judge whether staleness means archive, refresh or leave alone.

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.