clickhouse21.7.11.3 SQL语法优化-prewhere替代where

说明

prewhere 和 where 关键字的作用相同,都是用来 过滤数据。

执行过程

  1. 首先只读取 prewhere 所需的列,进行数据过滤(由于列式存储,查询一列数据快)
  2. 过滤之后,再执行 select 查询列,补全其余查询字段

适用范围

prewhere 只支持 MergeTree 族系列引擎的表

应用场景

当 查询列 明显多于 筛选列 时,使用 prewhere 可提升十倍查询性能

prewhere 会自动优化执行过滤阶段的数据读取方式,降低IO操作

优化

默认情况下,会自动将 where 优化成 prewhere

注意:有时不能自动优化

推荐:手动使用 prewhere 关键字

例子

explain syntax select name from t_student_mt2 where age = 20

执行结果

SELECT name       
FROM t_student_mt2
PREWHERE age = 20

不能自动转换 prewhere 的情况

select查询列和where的谓词相同

select查询列 与 where 条件列相同:

explain syntax select age from t_student_mt2 where age = 20

执行结果:

SELECT age        
FROM t_student_mt2
WHERE age = 20

没有优化成 PREWHERE

使用了主键字段

explain syntax select * from t_student_mt where sid = 1

执行结果:

SELECT           
    sid,         
    name,        
    age,         
    height,      
    create_time  
FROM t_student_mt
WHERE sid = 1

没有优化成 PREWHERE

例子:更多查询条件

explain syntax select * from t_student_mt where age < 20 and height <182

执行结果:

SELECT                             
    sid,                           
    name,                          
    age,                           
    height,                        
    create_time                    
FROM t_student_mt                  
PREWHERE age < 20                  
WHERE (age < 20) AND (height < 182)

参考:https://blog.csdn.net/qq_40378034/article/details/120473116


原文出处:/show_1IX3R6RrFqKL.html