Sql Where语句的顺序是否影响性能?
构造查询时指定的顺序是否会影响性能?或者SQL执行智能过滤 例如,假设我有一个拥有200万条记录的表Employee:Sql Where语句的顺序是否影响性能?,sql,Sql,构造查询时指定的顺序是否会影响性能?或者SQL执行智能过滤 例如,假设我有一个拥有200万条记录的表Employee: Employee( emp_id, name, dept_id, country_id ) 不是说我想得到国家id 500和部门id 17的员工的id和姓名。 不让我们说在那个部门大约有30万人,在那个国家大约有100万人,但是符合这两个标准的结果是50万人 如果我这样做,会不会造成性能差异: SELECT * FROM employees where dept_id = 1
Employee( emp_id, name, dept_id, country_id )
不是说我想得到国家id 500和部门id 17的员工的id和姓名。
不让我们说在那个部门大约有30万人,在那个国家大约有100万人,但是符合这两个标准的结果是50万人
如果我这样做,会不会造成性能差异:
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
如果我这样做:
SELECT *
FROM employees
where country_id= 500 and dept_id = 17
假设后者将把表减少到100万,然后从那里开始做其余的事情
第一个查询将减少到300k,并从那里执行第二个筛选
但是,正如前面提到的,我不确定SQL motor是如何处理查询的。大多数现代RDMB在语句的
部分中的值顺序不会有问题,它们的查询优化器在大多数情况下会按照您描述的方式进行排序,以最大限度地提高性能
我知道,如果您选择了“错误”的顺序,一些较旧的RDBMS实际上会受到相当大的影响,但在过去十年中,这些RDBMS应该已经过时了。在上表中
如果有非聚集索引-
(国家/地区id、部门id、员工id)
然后,查询-
SELECT *
FROM employees
where country_id= 500 and dept_id = 17
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
会有更好的表现
及
如果有非聚集索引-
表中的(部门id、国家id、员工id)
然后,查询-
SELECT *
FROM employees
where country_id= 500 and dept_id = 17
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
会有更好的表现
如果没有非聚集索引
然后,查询-
SELECT *
FROM employees
where country_id= 500 and dept_id = 17
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
第二个过滤子集的数量越少,性能越好
更何况,
如果两个非聚集索引都存在
然后,查询-
SELECT *
FROM employees
where country_id= 500 and dept_id = 17
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
SELECT *
FROM employees
where dept_id = 17 and country_id= 500
对于数量较少的第二个筛选子集,它将具有更好的性能。它确实会产生影响,特别是当您的执行计划中有剩余谓词时,但大多数情况下,查询优化器将为您重新排序谓词
当然,这是假设您的索引和统计数据得到了良好的维护和更新,所以这是需要考虑的
进一步阅读:若你们并没有索引,那个么无论如何都会退回到全表扫描。你们知道,你们可以要求服务器向你们展示执行计划,它会向你们解释一切。