简体   繁体   中英

Indexed Query Optimisation = SQL

This is a part of my past exam questions -

Optimise the following and assume there is an index on Members.lname :

SELECT fname, lname 
FROM Members 
WHERE lname <> 'Rogers' 
  AND memberType='Student'; 

I have therefore tried:

SELECT fname, lname 
FROM Members 
WHERE lname > 'Rogers' OR lname < 'Rogers'AND memberType='Student'; 

I tried this as splitting the <> forces the use of the index - my answer is however wrong. I was wondering if anyone could help and point me in the right direction?

In my opinion the original query itself cannot be optimized.

That there is an index on lname should have no impact on the query. All members will have a name and few members will be Rogers. So the DBMS should not use the index, but simply read the full table.

"Optimise the following", however, may allow to optimize the query indirectly by creating another index. This index should at least contain and start with memberType :

create index idx1 on members (membertype);

Whether this index will be used for the query will probably depend on what's in the table. If 99% of the members are students, the DBMS should read the full table instead. If it's only few students (say 3%) then using the index makes sense, and the DBMS would use the index to find the students in the table and then check lname in the record.

Having said this, we might want this instead:

create index idx2 on members (membertype, lname);

so the DBMS reads the index, finds the students, sees immediately if the name is Rogers, and only accesses the table for the desired records.

An even better index still would be a covering index containing all columns in question, so the table doesn't have to be read anymore, as all the information is in the index:

create index idx3 on members (membertype, lname, fname);

As mentioned, the DBMS may still read the full table instead when it assumes that most records will match anyway. Indexes are only an offer to the DBMS which it may use or not.

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