Question

A simple question on how database Indexes work.

Suppose i have a table 'Student' with columns id(primary_key), name and GPA. Assume that i have an index on id and on no other columns

Now if i query for a record using name and GPA(not with id), it has to search all records for a match. what is the advantage of index here ?

Are the indexes effective only when the query contains the indexed columns ?

Was it helpful?

Solution

if i query for a record using name and GPA(not with id), it has to search all records for a match. what is the advantage of index here?

You are correct. There is no advantage, except that unique indexes may also enforce uniqueness

Are the indexes effective only when the query contains the indexed columns?

Basically yes for finding matching rows, although indexes can also be used to help sorting if the order by contains an indexed column

OTHER TIPS

Just to add some examples to Bohemian's answer (and assuming a SQL RDBMS):

  1. An index IX1 on Student(name) will benefit the following query:

    SELECT * FROM Student WHERE name = 'Bloggs';

  2. Similarly you would need an index say IX2 on Student(GPA) for

    SELECT * FROM Student WHERE GPA between 1 and 2;

  3. If you have both the above indexes IX1 and IX2, SQL will then 'choose' between either in a query like:

    SELECT * FROM Student WHERE name = 'Bloggs' and GPA between 1 and 2;

  4. A query which ONLY uses fields in the index can be serviced entirely from an index (i.e. there is no need for SQL to internally 'join' back into the table or cluster). e.g. the below will be serviced entirely from IX1, because name is in the index.

    SELECT name FROM Student WHERE name = 'Bloggs';

  5. There must be good 'selectivity' in an index in order for SQL to use the index. e.g. if EVERYONE in your database has a name 'Bloggs', then SQL will most likely bypass the index and scan the table instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top