近期遇到一个日志表记录了几年数据,数据量较大(几亿数据),导致查询等操作较慢,为了提高效率,决定删除部分历史数据,想了三种方法如下:
通用步骤(每种方法之前先运行以下备份脚本):
1、备份 2021年之前数据
create table table_log_b2020 as select * from table_log a where a.logtime<date'2021-1-1';
2、备份2021年数据
create table table_log_2021 as select * from table_log a where a.logtime>=date'2021-1-1';
1、drop table ,然后再create table,插入数据
1、drop table
drop table table_log
2、create table table_log
3、插入2021年数据
insert into table_log select * from table_log_b2021;
2、使用delete批量删除
1、先去掉表索引,因为索引可能会影响删除效率
2、批量执行删除语句,也可以以存过方式直接运行,按照数量删除
delete from table_log a where a.logtime<date'2021-1-1' and rownum<5000000
每500万一次,没去索引之前大约耗时85秒,删掉索引之后大约耗时50
3、 使用truncate table ,然后再插入数据
1、truncate table
truncate table table_log 耗时0.5s
2、插入2021年数据
insert into table_log select * from table_log_b2021; 耗时 0.095s
第一种涉及到删表结构,公司相关规定不可这么做,第二种效率较为低
综合考虑使用了第三种,效率较为可观 ,秒秒钟把数据干干净。