软件开发Db2

db2 fetch first查询结果每次是否一致?

想问一下如果每天有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查的结果也还是一样的

参与12

2同行回答

cfpl_900cfpl_900联盟成员数据库管理员安信证券
不知道您的DB2是什么版本?但是从9.7以来,没有加order by的话,两次执行一样的SQL返回的行顺序未必会一致。影响的因素有很多:表的统计信息,索引的变化等等。详见:Row order differences in result tables - IBM Documentation至于您说的转移每天的100w数据,分10次insert和delete...显示全部

不知道您的DB2是什么版本?
但是从9.7以来,没有加order by的话,两次执行一样的SQL返回的行顺序未必会一致。
影响的因素有很多:表的统计信息,索引的变化等等。详见:
Row order differences in result tables - IBM Documentation
至于您说的转移每天的100w数据,分10次insert和delete,可能是因为insert和delete之间,没有任何影响目标表的语句正在执行,假如之间如上所说表数据更新,统计信息变化,索引变化,都有可能导致插入和删除的数据误差。

收起
证券 · 2023-02-08
leo_wynleo_wyn商业智能工程师Security
来自官方文档的解释:https://www.ibm.com/docs/en/db2-for-zos/12?topic=subselect-fetch-clauseDetermining 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 ...显示全部

来自官方文档的解释:
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.

收起
系统集成 · 2023-02-15

ChatGPT 回答

针对您的问题,我可以提供以下建议:

  1. 首先,您需要明确的是,fetch语句是没有默认排序的,如果您需要按照某个字段排序,需要显式地使用order by语句。
  2. 其次,如果您在测试环境中出现了数据不一致的问题,可能是由于并发操作导致的。在生产环境中,可能由于数据量较小或者并发量较低,所以没有出现问题。建议您在测试环境中增加并发量,或者使用更高版本的DB2,以获得更好的性能和稳定性。
  3. 另外,您的转移数据操作使用了事务,这是一个好的实践。但是,如果您的事务过大,可能会导致锁定表或者死锁等问题。建议您使用更小的事务,或者使用分布式事务来处理这个问题。
  4. 最后,建议您使用DB2的监控工具来监控数据库的性能和状态,以及查看是否有异常情况发生。如果出现问题,可以及时采取措施进行修复。

提问者

jiangnanage
java开发小白
擅长领域: 数据库存储灾备

相关问题

相关资料

相关文章

问题状态

  • 发布时间:2023-02-07
  • 关注会员:3 人
  • 问题浏览:2170
  • 最近回答:2023-02-15
  • X社区推广