Jump to content

Is an 'initial' field useful?


svivian

Recommended Posts

In my database I have several tables with a 'name' field. I added an 'initial' field for use on pages where I selected based on the first letter. This was before I leant about indexing.

 

Just wondering if what I have done is worthwhile or if simply indexing the name field would be just as fast?

Link to comment
Share on other sites

If you want to index just the first character of a column you can use the following:

CREATE INDEX `<name of index>` ON <table> (<column name>(1));

 

This will create an index on the first letter of the column. Meaning you can find all the names that contain 'F' as their first letter ( for example) faster.

i.e.

SELECT name 
FROM <table>
WHERE RIGHT(name,1) = 'F';

 

OR

SELECT name 
FROM <table>
WHERE name LIKE 'F%';

 

Hope that helps.

Link to comment
Share on other sites

OK thanks. Two more questions:

1. If I'm already indexing my 'name' field, I don't need to add a second index for the first letter as well, do I?

2. Is there a difference between a normal index and a unique index, besides the unique constraint? In other words, is the unique index still optimised for eg where clauses in the same way?

Link to comment
Share on other sites

1) Not unless you're expecting to offer people the option of searching by name first initial, in which case, yes you DO want to index the first letter of the name.

 

2) The difference as you suggested between a normal INDEX and a UNIQUE INDEX is indeed the uniqueness, however think about this logically.

If the value is UNIQUE then there is only 1 of the value in the WHOLE table EVER! So as far as MySQL is concerned if you ask it for a particular name that has a UNIQUE INDEX on it, then it knows EXACTLY where that is, and will only ever examine 1 row.

However, if you have a normal INDEX there is the possibility that you're looking at more than 1 row (because non-unique means there can be more than 1). Meaning MySQL will probably expect to have to examine more than 1 row.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.