Search code examples
postgresqldatabase-metadata

How to find out when data was inserted to Postgres?


I have inherited an existing Postgres database full of data. Most of the data has a 'created_date' column value. Some of the earlier data was inserted before this was being tracked.

Is there a Postgres metadata table hidden away somewhere that tracks when INSERT queries were done?


Solution

  • Postgres 9.5 or later

    You can enable track_commit_timestamp in postgresql.conf (and restart) to start tracking commit timestamps. Then you can get a timestamp for your xmin. Related answer:

    Postgres 9.4 or older

    There is no such metadata in PostgreSQL unless you record it yourself.

    You may be able to deduce some information from the row headers (HeapTupleHeaderData), in particular from the insert transaction id xmin. It holds the ID of the transaction in which the row was inserted (needed to decide visibility in PostgreSQL's MVCC model). Try (for any table):

    SELECT xmin, * FROM tbl LIMIT 10;
    

    Some limitations apply:

    • If the database was dumped and restored then, obviously, the information is gone - all rows are inserted in the same transaction.
    • If the database is huge / very old / very heavily written, then it may have gone through transaction ID wraparound, and the order of numbers in xmin is ambiguous.

    But for most databases you should be able to derive:

    • the chronological order of INSERTs
    • which rows were inserted together
    • when there (probably) was a long period of time between inserts

    No timestamp, though.