简体   繁体   中英

Keep the last 20 records and delete other records in oracle sql

I want to keep the last 20 records in VMR table and delete all other records. The VMR table has 5000000 records and its growing. I also have create_date column which has date datatype in VMR table and it has non unique index. I tried using rownum to delete the records and keep the last 20 records using below query but its taking too much time for deletion. Is there any other way to run the query faster.

delete from VMR
 where rowid not in 
       (select rowid
          from VMR
         where rownum <=20);

Just to show an alternative:

-- get 20 last records and remember them
create table vmr20 as
  select * from vmr order by create_date desc fetch first 20 rows only;

-- empty table via DDL which should be fastest
truncate vmr;

-- re-insert the last 20 rows
insert into vmr
  select * from vmr20;

-- delete temp table
drop table vmr20;

Try using ROW_NUMBER()

WITH CTE AS (
SELECT t.*,
       ROW_NUMBER() OVER(ORDER BY create_date DESC) as rnk
FROM VMR t)
DELETE FROM CTE 
WHERE CTE.rnk > 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM