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

后端 未结 6 1516
予麋鹿
予麋鹿 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:42

    Assuming you want to delete ANY 10 records (without the ordering) you could do this:

    DELETE FROM logtable as t1 WHERE t1.ctid < (select t2.ctid from logtable as t2  where (Select count(*) from logtable t3  where t3.ctid < t2.ctid ) = 10 LIMIT 1);
    

    For my use case, deleting 10M records, this turned out to be faster.

提交回复
热议问题