To consider a table with millions records and the table schema:
CREATE TABLE `foos` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`foo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `foo_UNIQUE` (`foo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Ton of this query executes every second
SELECT 1 FROM foos WHERE foo=?
If no record finds, this query will be executed:
INSERT INTO foos(foo) VALUES(?)
The average length of foo
less than 20. To optimize performance, a hashing field is considered to add with md5(foo)
and drop the unique key.
ALTER TABLE foos DROP INDEX foo_UNIQUE;
ALTER TABLE foos ADD INDEX `foo_IDX` (`hash`);
And the query will be changed as:
SELECT 1 FROM foos WHERE hash=?
If no record finds, this query will be executed:
INSERT INTO foos(foo, hash) VALUES(?, ?)
The Question is: Will the SELECT
query run faster, since average length of foo
less than 20 but hashing field length is always 32?
SELECTs
will be insignificant. The avg length of the column will make a slight difference; however the various overheads will dominate.