I've been studying indexes and trying to understand how they work and how I can use them to boost performance, but I'm missing something.
I have the following table:
Person:
| Id | Name | Email | Phone |
| 1 | John | E1 | P1 |
| 2 | Max | E2 | P2 |
I'm trying to find the best way to index the columns Email
and Phone
considering that the queries will (most of the time) be of the form
[1] SELECT * FROM Person WHERE Email = '...' OR Phone = '...'
[2] SELECT * FROM Person WHERE Email = ...
[3] SELECT * FROM Person WHERE Phone = ...
I thought the best approach would be to create a single index using both columns:
CREATE NONCLUSTERED INDEX [IX_EmailPhone]
ON [dbo].[Person]([Email], [PhoneNumber]);
However, with the index above, only the query [2] benefits from an index seek, the others use index scan.
I also tried to create multiple index: one with both columns, one for email, and one for email. In this case, [2] and [3] use seek, but [1] continues to use scan.
Why can't the database use index with an or? What would be the best indexing approach for this table considering the queries?
SELECT *
too, so it needs to get back to the table to get the other columns anywaySELECT *
is just a shortcut to useSELECT <list every column here>
, so the argument is the sameSELECT [a column that's in the index]
. There are just too few rows in the table