Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query rows by time of creation?

I have a table that contains no date or time related fields. Still I want to query that table based on when records/rows were created. Is there a way to do this in PostgreSQL?

I prefer an answer about doing it in PostgreSQL directly. But if that's not possible, can hibernate do it for PostgreSQL?

like image 349
user1467855 Avatar asked Jul 27 '12 17:07

user1467855


1 Answers

Basically: no. There is no automatic timestamp for rows in PostgreSQL.

I usually add a column like this to my tables (ignoring time zones):

ALTER TABLE tbl ADD COLUMN log_in timestamp DEFAULT localtimestamp NOT NULL;

As long as you don't manipulate the values in that column, you got your creation timestamp. You can add a trigger and / or restrict write privileges to avoid tempering with the values.

Second class options

  • If you have a serial column, you could at least tell with some probability in what order rows were entered. That's not 100% reliable, because the values can be changed by hand, and applications can get values from the sequence and INSERT out of order.

  • If you created your table WITH (OIDS=TRUE), then the OID column could be some indication - unless your database is heavily written and / or very old, then you may have gone through OID wrap-around and later rows can have a smaller OID. That's one of the reasons, why this feature is hardly used any more.

    The default depends on the setting of default_with_oids I quote the manual:

The parameter is off by default; in PostgreSQL 8.0 and earlier, it was on by default.

  • If you have not updated your rows or went through a dump / restore cycle, or ran VACUUM FULL or CLUSTER or .. , a plain SELECT * FROM tbl returns all rows in the order they were entered. But this is very unreliable and implementation-dependent. PostgreSQL (like any RDBMS) does not guarantee any order without an ORDER BY clause.
like image 118
Erwin Brandstetter Avatar answered Oct 15 '22 06:10

Erwin Brandstetter