PostgreSQL - retrieving items in order they were stored

前端 未结 2 1994
悲哀的现实
悲哀的现实 2021-01-23 14:59

Folks, I have the following table:

CREATE TABLE IF NOT EXISTS users(
 userid           CHAR(100)         NOT NULL,
 assetid          text              NOT NULL,
         


        
相关标签:
2条回答
  • 2021-01-23 15:13

    To expand on Mark's correct answer, PostgreSQL doesn't keep a row timestamp, and it doesn't keep rows in any particular order. Unless you define your tables with a column containing the timestamp they were inserted at, there is no way to select them in the order they were inserted.

    PostgreSQL will often return them in the order they were inserted in anyway, but that's just because they happen to be in that order on the disk. This will change as you do updates on the table, or deletes then later inserts. Operations like vacuum full also change it. You should never, ever rely on the order without an explicit order by clause.

    Also, if you want the insertion timestamp to differ for rows within a transaction you can use clock_timestamp instead of now(). Also, please use the SQL-standard current_timestamp instead of writing now().

    0 讨论(0)
  • 2021-01-23 15:14

    Assuming your date column holds different timestamps for each item, by using the ORDER BY clause:

    SELECT * FROM users WHERE userid=foo ORDER BY "date";
    

    However, if you inserted a large number of records in a single transaction, the date column value will probably be the same for all of them - if so, there is no way to tell which was inserted first (from the information given).

    0 讨论(0)
提交回复
热议问题