SQL删除表中最旧的记录

时间:2010-06-28 08:57:21

标签: sql oracle

我正在寻找一个在oracle表上运行的SQL查询,该表将在表中保留n条记录并删除其余的

我尝试了以下

delete from myTable where pk not in 
(SELECT pk FROM myTable where rownum <5 order by created DESC)

但似乎我在嵌套选择中不能有order by

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:13)

当您使用ORDER BY和ROWNUM时,首先应用ROWNUM,因此您无法获得预期的结果。您可以将SQL修改为:

delete from myTable where pk not in 
( SELECT pk FROM 
   ( SELECT pk FROM myTable  order by created DESC)
  where rownum <5
)

还有很多其他方法可以写这个。如果表很大并且大多数行将被删除,那么这可能会更快:

delete from myTable where created < 
( SELECT MIN(created) FROM 
   ( SELECT created FROM myTable order by created DESC)
  where rownum <5
)