How do I delete a fixed number of rows with sorting in PostgreSQL?

后端 未结 6 1506
予麋鹿
予麋鹿 2020-11-28 03:27

I\'m trying to port some old MySQL queries to PostgreSQL, but I\'m having trouble with this one:

DELETE FROM logtable ORDER BY timestamp LIMIT 10;

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:51

    You could try using the ctid:

    DELETE FROM logtable
    WHERE ctid IN (
        SELECT ctid
        FROM logtable
        ORDER BY timestamp
        LIMIT 10
    )
    

    The ctid is:

    The physical location of the row version within its table. Note that although the ctid can be used to locate the row version very quickly, a row's ctid will change if it is updated or moved by VACUUM FULL. Therefore ctid is useless as a long-term row identifier.

    There's also oid but that only exists if you specifically ask for it when you create the table.

提交回复
热议问题