Mysql – Speed-up lookup of a row with prefix pattern

MySQLperformancequery-performance

Say I have these rows in one UNIQUE column:

  • 202101XXXXX
  • 202101XXXXX
  • 202102XXXXX
  • 202102XXXXX
  • 202103XXXXX
  • 202103XXXXX

The first 6 digits are year and month (YYYYMM), and the XXXXX part are random digits. They are UNIQUE. Let's say there are millions of rows like these.

I need to lookup a certain row e.g., 20210312345, is there a way I could tell MySQL to not look at the whole table and just search on rows with the 202103 prefix? And, if that was possible, would it actually speed up the query?

Best Answer

This is how indexing essentially works. If you create an index on that column, the data will be sorted by the value, which effectively is on the prefix first and then the suffix.

The other thing you can do is either store only the suffix part (the XXXXX) of the value in it's own column too, either from the application that loads the data or using a Stored Generated Column and then create the index on that field. Doing that allows you to do an exact match search on a more unique value.