· Markdown version

Schema drift in PostgreSQL: detect dropped, renamed and retyped columns with SQL

postgres schema drift

Schema drift is a table's columns changing under you: a column dropped, renamed, or retyped by an app migration or an upstream tool. Queries that name the old column fail loudly. The dangerous cases are quiet: SELECT * loads, COALESCE(old_col, 0) patterns, or a BI tool that shows blanks instead of errors.

To catch it in Postgres, take a daily snapshot of every table's columns from pg_attribute, keep the history in a small table, and diff the last two snapshots. Use the column number (attnum) as the join key, not the name. That one choice is what lets you tell a rename from a drop.

The SQL below was run on PostgreSQL 17.12.

Why attnum and not the column name

  • Each column has a number, attnum, starting at 1.
  • ALTER TABLE ... RENAME COLUMN keeps the same attnum. Same number, new name: that's a rename.
  • DROP COLUMN doesn't renumber. The old number is marked attisdropped and never reused. If someone drops a column and adds one back with the same name, it gets a new number, so you see a removal plus an addition, which is correct: the old data is gone.
  • information_schema.columns exposes ordinal_position, but joining on names can't separate "renamed" from "dropped one, added another".

1. Create the history table

CREATE SCHEMA IF NOT EXISTS monitoring;

CREATE TABLE monitoring.column_snapshots (
  snapshot_at   timestamptz NOT NULL,
  table_schema  text NOT NULL,
  table_name    text NOT NULL,
  attnum        smallint NOT NULL,
  column_name   text NOT NULL,
  data_type     text NOT NULL,
  is_nullable   boolean NOT NULL,
  PRIMARY KEY (snapshot_at, table_schema, table_name, attnum)
);

2. Snapshot every table's columns (run daily)

INSERT INTO monitoring.column_snapshots
SELECT now(), n.nspname, c.relname, a.attnum, a.attname,
       format_type(a.atttypid, a.atttypmod), NOT a.attnotnull
FROM pg_attribute a
JOIN pg_class c     ON c.oid = a.attrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','m','f')
  AND n.nspname NOT IN ('pg_catalog','information_schema','monitoring')
  AND n.nspname NOT LIKE 'pg_toast%'
  AND a.attnum > 0
  AND NOT a.attisdropped;
  • relkind covers tables, partitioned tables, views, materialized views, and foreign tables. Narrow it if you only care about tables. On 17.12 a partitioned table, a view, and a materialized view were all included.
  • format_type gives readable types with modifiers, such as numeric(10,2) or character varying(50), so widening a column shows up too.
  • Run it from cron, an Airflow task, or a dbt run-operation. Daily is enough for most teams. Run it right after your main load if you want drift caught before dashboards refresh.
  • Privileges: pg_attribute lists columns of every table, even ones the role can't SELECT from. information_schema.columns only shows tables the role has privileges on, so a snapshot built on it can silently miss tables. On 17.12 a role with no privileges on public.secret_orders still read id and secret from pg_attribute, and information_schema.columns returned nothing until that role was granted SELECT.

3. Diff the last two snapshots

WITH runs AS (
  SELECT DISTINCT snapshot_at FROM monitoring.column_snapshots
  ORDER BY snapshot_at DESC LIMIT 2
),
cur  AS (SELECT * FROM monitoring.column_snapshots WHERE snapshot_at = (SELECT max(snapshot_at) FROM runs)),
prev AS (SELECT * FROM monitoring.column_snapshots WHERE snapshot_at = (SELECT min(snapshot_at) FROM runs))
SELECT coalesce(c.table_schema, p.table_schema) AS table_schema,
       coalesce(c.table_name,  p.table_name)  AS table_name,
       CASE
         WHEN p.attnum IS NULL THEN 'added'
         WHEN c.attnum IS NULL THEN 'removed'
         WHEN c.column_name <> p.column_name THEN 'renamed'
         WHEN c.data_type   <> p.data_type   THEN 'type_changed'
         ELSE 'nullability_changed'
       END AS change,
       p.column_name AS old_name, c.column_name AS new_name,
       p.data_type AS old_type, c.data_type AS new_type,
       p.is_nullable AS old_nullable, c.is_nullable AS new_nullable
FROM cur c
FULL JOIN prev p
  ON  p.table_schema = c.table_schema
  AND p.table_name   = c.table_name
  AND p.attnum       = c.attnum
WHERE (SELECT count(*) FROM runs) = 2
  AND (p.attnum IS NULL OR c.attnum IS NULL
       OR c.column_name <> p.column_name
       OR c.data_type   <> p.data_type
       OR c.is_nullable <> p.is_nullable)
ORDER BY 1, 2, change;

It returns no rows when nothing changed, so you can alert on any rows. One snapshot returned no rows, and two identical snapshots returned no rows. On our test table, after a migration that added channel, dropped coupon_code, renamed status to order_status, widened amount from numeric(10,2) to numeric(12,2), and made created_at NOT NULL, it returned:

Sample diff for public.orders after adding channel, dropping coupon_code, renaming status, widening amount, and making created_at NOT NULL.
tablechangeoldnew
public.ordersaddedchannel text
public.ordersnullability_changedcreated_at nullablecreated_at NOT NULL
public.ordersremovedcoupon_code text
public.ordersrenamedstatusorder_status
public.orderstype_changedamount numeric(10,2)amount numeric(12,2)
  • A new table shows all its columns as added. A dropped table shows them all as removed. On 17.12, creating public.shipments and dropping public.orders between snapshots listed every shipments column as added and every orders column as removed. Group by table if you want one "table created/dropped" line instead.
  • Dropping a column and adding it back under the same name returned both removed and added, with a new attnum on the added row.
  • If a column is renamed and retyped between snapshots, the query reports renamed only (the first match wins). Renaming order_status to state and changing it from text to character varying(40) produced one renamed row, and the type columns still showed both types. Split the CASE into separate checks if you need both labels.
  • Prune old snapshots, for example keep 90 days: DELETE FROM monitoring.column_snapshots WHERE snapshot_at < now() - interval '90 days';

4. Turn it into a failing test in dbt

A dbt singular test fails when its query returns rows. Save the diff query as tests/assert_no_schema_drift.sql (drop the trailing semicolon), and dbt test / dbt build will fail on any drift since the last snapshot. Run the snapshot step before the test, or the test compares yesterday's two snapshots.

Two dbt features help with your own models, but they don't watch sources:

  • Model contracts (contract: {enforced: true}) make dbt check that a model's columns match the name and data_type in YAML before it builds the model. They don't apply to sources, seeds, or snapshots, and they ignore size and precision, so varchar(50) to varchar(255) won't fail.
  • `on_schema_change` on incremental models: ignore (default), fail, append_new_columns, or sync_all_columns. It reacts when your model's columns change, tracks top-level columns only, and never backfills new columns on old rows.

So if an upstream app renames a column in a source table, contracts and on_schema_change won't tell you. The snapshot diff will.

5. Optional: log every DDL change as it happens

If you control the database and have a superuser, an event trigger records each change with who made it and when. Only superusers can create event triggers, so this often isn't possible on managed services or someone else's database. The daily snapshot does not need a superuser: any role that can read pg_attribute and insert into the history table can run it.

CREATE TABLE monitoring.ddl_log (
  logged_at       timestamptz NOT NULL DEFAULT now(),
  username        text        NOT NULL DEFAULT current_user,
  command_tag     text,
  object_type     text,
  object_identity text
);

CREATE OR REPLACE FUNCTION monitoring.log_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
DECLARE r record;
BEGIN
  FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() LOOP
    INSERT INTO monitoring.ddl_log (command_tag, object_type, object_identity)
    VALUES (r.command_tag, r.object_type, r.object_identity);
  END LOOP;
END $$;

CREATE EVENT TRIGGER log_ddl ON ddl_command_end
  WHEN TAG IN ('ALTER TABLE', 'CREATE TABLE', 'DROP TABLE')
  EXECUTE FUNCTION monitoring.log_ddl();

EXECUTE FUNCTION in CREATE EVENT TRIGGER requires PostgreSQL 11 or newer. Older versions used EXECUTE PROCEDURE. PostgreSQL 17 still accepts EXECUTE PROCEDURE.

On 17.12, CREATE TABLE public.orders logged CREATE TABLE | table | public.orders. ALTER TABLE public.orders ADD COLUMN region text logged ALTER TABLE | table | public.orders (the table, not the new column). Renaming region to sales_region logged ALTER TABLE | table column | public.orders.sales_region. ALTER TABLE ... DROP COLUMN logged only the table, ALTER TABLE | table | public.orders, and DROP TABLE produced no row. pg_event_trigger_ddl_commands() doesn't list dropped objects. Add a sql_drop event trigger using pg_event_trigger_dropped_objects() if you need those. The log tells you who changed what. The snapshot diff tells you what the table looks like now. They complement each other.

Where Row Monitor fits

If you'd rather not maintain the snapshot job, the diff, and the alerting, Row Monitor runs a schema check on the Postgres, BigQuery, or Snowflake tables you name. The first clean check stores each table's columns, type names, and nullability. A later check opens an anomaly when a column is added or removed, or when its type name or nullability changes, even if the job that loaded the table stayed green. The check joins columns by name, so a rename shows up as one removed column and one added column. On Postgres the type name comes from information_schema.columns, so a precision-only change such as numeric(10,2) to numeric(12,2) does not alert.

Slack or email includes the column diff. Open the anomaly for a plain-English explanation and a dbt schema.yml snippet for the columns that changed. Postgres access is a role you grant SELECT. Row Monitor does not write to your warehouse. Scheduled table checks run once a day on every plan, and you can run one yourself.

Prices are in US dollars. Free is US$0 a month for 3 tables, Pro is US$39 a month for 50 tables, and Team is US$99 a month for 500 tables.

FAQ

What is schema drift?

An unplanned change to a table's structure, such as a dropped, renamed, or retyped column, that downstream queries, models, or dashboards weren't updated for.

How do I detect schema changes in PostgreSQL?

Snapshot pg_attribute (or information_schema.columns) on a schedule into a history table and diff the latest two snapshots. For a real-time audit trail, a superuser can add a ddl_command_end event trigger. pg_attribute still lists columns the role cannot SELECT. information_schema.columns does not.

How can I tell a renamed column from a dropped one?

Join snapshots on attnum. A rename keeps the column's number. A drop retires it, and a re-added column gets a new number, so the diff shows both removed and added.

Does a column type change break my pipeline?

Sometimes loudly (a cast fails), often quietly: widening a numeric, switching boolean to integer, or text to varchar can change results without an error. That's why the diff compares the full type, including modifiers.

Does dbt detect source schema changes?

Not by default. Model contracts and on_schema_change cover your own models. Contracts ignore size and precision and don't apply to sources, seeds, or snapshots. For sources you need a check like the snapshot diff or a monitoring tool.

Can I run this with a read-only user?

Yes for the diff logic: reading pg_attribute needs no table privileges. The role does need somewhere to write snapshots, such as a small monitoring schema, or keep the history outside the database.