简体   繁体   中英

how the columns order matters while index creation in sql server?

I have created one table EMP (name varchar(10),address varchar(10)) and Two indexes on both columns with only difference is order of column is changes. Index1(name,address) and index2(adress,name) and I ran select * from emp where name='' and address='' and it utilizes index2 which is obvious then i flush the cache (even restarted my sql service) changed the order as select * from emp where address='' and name='' an this time i thought index1 will be utilized but it utilizes the same index index2.

Now second Thing- I dropped this table and recreated the same table only with difference that i created index2 first and then created index1 as same order above and do the same process from case1 and this time it utilizes index1

Question is - Does the order in where filter not matters in such case? its always taking index into considerations which got created at last, My understanding was It reads the execution from right to left but its not the case here?

For your particular query, either index can be used. SQL Server arbitrarily chooses one of them -- I don't think there is a preference for one over the other.

On the other hand, if you had a query like this:

where name = ? and address like 'A%'

Then the best index is (name, address) .

Or like this:

where address = ? and name like 'A%'

Then the best index is (address, name) .

The order of the comparisons in the WHERE is independent of the index usage (unless there is some meaningless impact based on the ordering of equivalent indexes in the optimizer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM