20.6.3版本后的功能,此前看执行计划需要设置日志级别为trace才可以看到,并且只能真正执行SQL后,在执行日志里查看。
基本语法
EXPLAIN [AST | SYNTAX | QUERY TREE | PLAN | PIPELINE | ESTIMATE | TABLE OVERRIDE] [setting = value, ...]
[
SELECT ... |
tableFunction(...) [COLUMNS (...)] [ORDER BY ...] [PARTITION BY ...] [PRIMARY KEY] [SAMPLE BY ...] [TTL ...]
]
[FORMAT ...]
- PLAN
explain后默认跟的是plan,(不写的话就是PLAN),用于查看执行计划;
header:打印计划中各个步骤的head说明,默认关闭,默认值0
description:打印计划中各个步骤的描述,默认开启,默认值1
action:打印计划中各个步骤的详细信息,默认关闭,默认值0 - AST
用于查看语法树 - SYNTAX
用户优化语法 - PIPELINE
用于查看执行过程
PLAN
查看执行计划:
explain select database,table,count(1) cnt from system.parts where database in ('datasets','system') group by database,table order by database,cnt desc limit 2 by database;
通过缩进看执行步骤,从下往上执行。
打开全部参数的执行计划示例:
explain header=1, actions=1,description=1 SELECT number from system.numbers limit 10;
AST语法树
explain ast select number from system.numbers limit 10;
SYNTAX语法优化
// 先做一次查询
select number = 1 ? 'hello' : (number = 2 ? 'world' : 'atguigu') from numbers(10);
// 查看语法优化
explain syntax select number = 1 ? 'hello' : (number = 2 ? 'world' : 'atguigu') from numbers(10);
// 开启三元运算符优化
set optimize_if_chain_to_multiif = 1;
// 再次查看语法优化
explain syntax select number = 1 ? 'hello' : (number = 2 ? 'world' : 'atguigu') from numbers(10);
// 返回优化后的语句
select multiIf(number = 1, 'hello', number = 2, 'world', 'atguigu') from numbers(10);
查看PIPELINE
explain pipeline select sum(number) from numbers_mt(100000) group by number % 20;
// 打开其他参数
explain pipeline header=1,graph=1 select sum(number) from numbers_mt(10000) group by number%20;
老版本只能从日志中看trace