Is it possible to have function-based index in MySQL?

No, not in a general sense, I don’t believe even 5.6 (the latest version when this answer was first written) has this functionality. It’s worth noting that 8.0.13 and above now support functional indexes, allowing you to achieve what you need without the trigger method described below.

If you are running an older version of mysql, it is possible to only use the leading part of a column (this functionality has been around for a long time), but not one starting at the second or subsequent characters, or any other more complex function.

For example, the following creates an index using the first five characters of a name:

create index name_first_five on cust_table (name(5));

For more complex expressions, you can achieve a similar effect by having another column with the indexable data in it, then using insert/update triggers to ensure it’s populated correctly.

Other than the wasted space for redundant data, that’s pretty much the same thing.

And, although it technically violates 3NF, that’s mitigated by the use of triggers to keep the data in sync (this is something that’s often done for added performance).

Leave a Comment