
Originally Posted by
djr33
Interesting. I haven't ever tried that [multiple indexes]. I guess it takes more storage space?
yeah, sure. but if it saves you from doing a full table scan, it's certainly worth it. You shouldn't index "everything" (that is a waste), but anything that one of your queries use should be indexed, if possible. For example:
Code:
CREATE TABLE phoneNumbers(
user INT NOT NULL
,country VARCHAR(2) NOT NULL
,area VARCHAR(3) NOT NULL
,number VARCHAR(7) NOT NULL
,bestTimeToCall TIME NOT NULL
,PRIMARY KEY( country,area,number )
);
The primary key is an identifier for the row (all phone numbers *must* be different, so it's a natural choice - no need for an artificial "id" column). MySQL will use it to make sure you don't enter duplicate phone numbers. If you'd like to (for some reason), you can check if a phone number exists in the DB like so:SELECT 1 FROM phoneNumbers WHERE country=? AND area=? AND number=?
And MySQL will use the primary key index to check. It won't look at the table at all.
Say you want to be able to look up all phone numbers belonging to a certain user - SELECT country,area,number FROM phoneNumbers WHERE user=?
Add an index:
Code:
CREATE TABLE phoneNumbers(
user INT NOT NULL
,country VARCHAR(2) NOT NULL
,area VARCHAR(3) NOT NULL
,number VARCHAR(7) NOT NULL
,bestTimeToCall TIME NOT NULL
,PRIMARY KEY( country,area,number )
,INDEX( user )
);
Now you have two indexes, with extra overhead to maintain, but you use both of them regularly and the time they save you more than make up for it.
Now, say you want to be able to select phone numbers you can call before lunch:SELECT country,area,phone FROM phoneNumbers WHERE HOUR( bestTimeToCall ) > 8 AND HOUR( bestTimeToCall ) < 12
You can index the `bestTimeToCall` column:
Code:
CREATE TABLE phoneNumbers(
user INT NOT NULL
,country VARCHAR(2) NOT NULL
,area VARCHAR(3) NOT NULL
,number VARCHAR(7) NOT NULL
,bestTimeToCall TIME NOT NULL
,PRIMARY KEY( country,area,number )
,INDEX( user )
,INDEX( bestTimeToCall )
);
But it won't do any good, because the index will include the column values, not the results of the HOUR() function. This is similar to the reason LIKE queries don't benefit from indexes.
Bookmarks