KingbaseES where 条件解析顺序
概述
KingbaseES 对于where 条件的解析严格遵守“从左到右”的原则,因此,对于选择性比较强的条件,进行最先过滤是有利于性能的。
一、KingbaseES
1、条件顺序影响执行效率
例子:
create table t1(id1 integer,id2 integer); insert into t1 select generate_series(1,1000000),generate_series(1,1000000);
条件顺序影响性能:经 id1 过滤掉的数据更多,放在前面效率更优。
test=# explain analyze select * from t1 where id2>1000000 and id1>9999000; QUERY PLAN -------------------------------------------------------------------------------------------------------------- Seq Scan on t1 (cost=0.00..194248.72 rows=1111116 width=8) (actual time=815.263..815.350 rows=1000 loops=1) Filter: ((id2 > 1000000) AND (id1 > 9999000)) Rows Removed by Filter: 9999000 Planning Time: 0.064 ms Execution Time: 815.391 ms (5 rows) test=# explain analyze select * from t1 where id1>9999000 and id2>1000000; QUERY PLAN ---------------------------------------------------------------------------------------------------------- Seq Scan on t1 (cost=0.00..194247.65 rows=899 width=8) (actual time=747.644..747.733 rows=1000 loops=1) Filter: ((id1 > 9999000) AND (id2 > 1000000)) Rows Removed by Filter: 9999000 Planning Time: 0.069 ms Execution Time: 747.773 ms (5 rows)
2、条件顺序影响SQL执行
例子:
create table t1(id1 varchar(10),id2 varchar(10)); insert into t1 values('123','abc'); test=# select * from t1 where id1=1 and id2=2; id1 | id2 -----+----- (0 rows) test=# select * from t1 where id2=2 and id1=1; ERROR: invalid input syntax for type integer: "abc"
问题分析:这里的语句实际 是:select * from t1 where to_number(id1)=1 and to_number(id2)=2 。语句在执行时,先根据 to_number(id1)=1 条件进行过滤,只有满足to_number(id1)=1条件,才 过来 to_number(id2)=2 条件。
语句1:to_number(123)=1 不满足,因此,没必要执行 to_number(id2)=2 ,不会报错
语句2:先执行 to_number(id2)=2 ,直接报错了。