I have a table of over 5 million rows. When i perform a select query it is taking around 20 seconds.
SELECT CompUID,Weburl FROM `CompanyTable` WHERE (Alias1='match1' AND Alias2='match2' )OR Alias3='match3' OR Alias4='match4'
Here is the table structure:
CREATE TABLE `CompanyMaster` (
`CompUID` int(11) NOT NULL AUTO_INCREMENT,
`Weburl` varchar(150) DEFAULT NULL,
`CompanyName` varchar(200) DEFAULT NULL,
`Alias1` varchar(150) DEFAULT NULL,
`Alias2` varchar(150) DEFAULT NULL,
`Alias3` varchar(150) DEFAULT NULL,
`Alias4` varchar(150) DEFAULT NULL,
`Created` datetime DEFAULT NULL,
`LastModified` datetime DEFAULT NULL,
PRIMARY KEY (`CompUID`),
KEY `Alias` (`Alias1`,`Alias2`,`Alias3`,`Alias4`)
) ENGINE=InnoDB AUTO_INCREMENT=5457968 DEFAULT CHARSET=latin1
Here is the EXPLAIN from that query:
--------+------------------------------------------------------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------+------+---------+------+---------+----------------------+
| 1 | SIMPLE | CompanyTable | ALL | Alias | NULL | NULL | NULL | 5255929 | Using where |
+----+-------------+----------+-------+---------------+------+---------+------+---------+----------------------+
I used the composite index Alias (Alias1,Alias2,Alias3,Alias4).
But i believe it's not the best one. Please suggest me the right indexing for this select query lookup.
OR Alias3='match3' OR Alias4='match4'is what is forcing the full table scan. This clause is essentially unindexed. In order to optimize this query, you'll need to add an index on Alias3 and Alias4.SELECT CompUID,Weburl FROMCompanyTable` use index(Alias) ...`. Does that make a difference in speeds?CompanyTablewhere Alias1='match1' AND Alias2='match2';" and "select count() fromCompanyTablewhere Alias1='match3'" and "select count(*) fromCompanyTablewhere Alias1='match4".