天天看點

where 子句的執行順序

 看代碼:

set statistics io on

set statistics time on

go

set statistics profile on

go

use pubs

select * from authors

where (au_fname like 'S%' or au_fname like 'a%')

and (state like 'CA' or state like 'UT')

and (cast(zip as int) > 90000)

select * from authors

where (au_fname like 'S%' or au_fname like 'a%')

and (cast(zip as int) > 90000)

and (state like 'CA' or state like 'UT')

select * from authors

where (cast(zip as int) > 90000)

and (au_fname like 'S%' or au_fname like 'a%')

and (state like 'CA' or state like 'UT')

目的:想驗證where語句的各個條件的查詢順序

環境:SQLServer 2005Express版本

步驟:顯示查詢計劃

結果:無一例外,都被統一成了這樣的代碼

|--Clustered Index Scan(OBJECT:([pubs].[dbo].[authors].[UPKCL_auidind]), WHERE:(CONVERT(int,[pubs].[dbo].[authors].[zip],0)>(90000) AND ([pubs].[dbo].[authors].[au_fname] like 'S%' OR [pubs].[dbo].[authors].[au_fname] like 'a%') AND ([pubs].[dbo].[authors].[state] like 'CA' OR [pubs].[dbo].[authors].[state] like 'UT')))

結論:貌似在2005之前的版本中,where子句的順序是從前往後的。但是又貌似在2005的版本中進行了優化,所有的順序都被統一成了以過濾能力進行排序的語句。

結論2:根據《T-SQL權威指南》,原本上,where子句的順序就不應該成為影響結果的因素。是以這樣推斷,where後面的子句肯定都被DBMS給優化了。

繼續閱讀