想问一下如果每天有100w数据,把 insert into 历史表 select * from 当天表 fetch first N rows only 和delete from 当前表 fetch fist N rows only 放在一个事务里每次从当前表转移10w数据到历史表循环转移10次,没加 order by,每次insert into 和delete 是有可能不同的数据因为每次fetch查出来的数据是有可能不一致的,但是为什么我这边生产上好几年一直这样转移数据好像没出现过问题,但是测试环境确实出现过数据不一致的问题,想问一下db2后面高版本有没有对fetch做优化或者查询结果有默认排序这种的,所以我这边order by没加,每次fetch查的结果也还是一样的
不知道您的DB2是什么版本?
但是从9.7以来,没有加order by的话,两次执行一样的SQL返回的行顺序未必会一致。
影响的因素有很多:表的统计信息,索引的变化等等。详见:
Row order differences in result tables - IBM Documentation
至于您说的转移每天的100w数据,分10次insert和delete,可能是因为insert和delete之间,没有任何影响目标表的语句正在执行,假如之间如上所说表数据更新,统计信息变化,索引变化,都有可能导致插入和删除的数据误差。
来自官方文档的解释:
https://www.ibm.com/docs/en/db2-for-zos/12?topic=subselect-fetch-clause
Determining a predictable set of rows to retrieve requires the specification of an ORDER BY clause with sort keys that would uniquely identify the sort order of each row in the intermediate result table. If the intermediate result table includes duplicate sort keys for some rows, the order of these rows is not deterministic. If there is no ORDER BY clause, the intermediate result table is not in a deterministic order. If the order of the intermediate result table is not deterministic, the set of rows retrieved is unpredictable. If both the fetch-clause and the ORDER BY clause are specified, the fetch-clause is processed on the ordered data.
收起针对您的问题,我可以提供以下建议: