Asume table A in MySQL 5.7, with index on the column name
: id name 1 Alice 2 Nancy...
Now finding out names with length greater than 5. The query is:
select * from A where length(name) >= 5;
However, if applying functions on column with index, then the index will not work. So how to optimize the query to hit the index?
Actually, MySQL 8+ finally supports functional indices, so you may add the following index here:
ALTER TABLE A ADD INDEX((LENGTH(name)));
On earlier versions of MySQL, you would need to get more creative. On MySQL 5.7, you could have added a new column name_length
to the A
table. When you insert a name, also insert the length, and then index the length column:
INSERT INTO A (name, name_length)
VALUES
('Gordon', 6);
CREATE INDEX idx ON A (name_length);
SELECT * FROM A WHERE name_length >= 5;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.