In this blog post, we’ll look at ways you can use MySQL 5.7 generated columns (or virtual columns) to improve query performance.
About two years ago I published a blog post about Generated (Virtual) Columns in MySQL 5.7. Since then, it’s been one of my favorite features in the MySQL 5.7 release. The reason is simple: with the help of virtual columns, we can create fine-grained indexes that can significantly increase query performance. I’m going to show you some tricks that can potentially fix slow reporting queries with GROUP BY and ORDER BY.
Recently I was working with a customer who was struggling with this query:
|
1 |
SELECT <br>CONCAT(verb, ' - ', replace(url,'.xml','')) AS 'API Call', <br>COUNT(*) as 'No. of API Calls', <br>AVG(ExecutionTime) as 'Avg. Execution Time', <br>COUNT(distinct AccountId) as 'No. Of Accounts', <br>COUNT(distinct ParentAccountId) as 'No. Of Parents' <br>FROM ApiLog <br>WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' <br>GROUP BY CONCAT(verb, ' - ', replace(url,'.xml','')) <br>HAVING COUNT(*) >= 1 ; |
The query was running for more than an hour and used all space in the tmp directory (with sort files).
The table looked like this:
|
1 |
CREATE TABLE `ApiLog` ( <br>`Id` int(11) NOT NULL AUTO_INCREMENT, <br>`ts` timestamp DEFAULT CURRENT_TIMESTAMP, <br>`ServerName` varchar(50) NOT NULL default '', <br>`ServerIP` varchar(50) NOT NULL default '', <br>`ClientIP` varchar(50) NOT NULL default '', <br>`ExecutionTime` int(11) NOT NULL default 0, <br>`URL` varchar(3000) NOT NULL COLLATE utf8mb4_unicode_ci NOT NULL, <br>`Verb` varchar(16) NOT NULL,<br>`AccountId` int(11) NOT NULL, <br>`ParentAccountId` int(11) NOT NULL, <br>`QueryString` varchar(3000) NOT NULL, <br>`Request` text NOT NULL, <br>`RequestHeaders` varchar(2000) NOT NULL, <br>`Response` text NOT NULL, <br>`ResponseHeaders` varchar(2000) NOT NULL, <br>`ResponseCode` varchar(4000) NOT NULL, <br>... // other fields removed for simplicity<br>PRIMARY KEY (`Id`),<br>KEY `index_timestamp` (`ts`),<br>... // other indexes removed for simplicity<br>) ENGINE=InnoDB;<br> |
We found out the query was not using an index on the timestamp field (“ts”):
|
1 |
mysql> explain SELECT CONCAT(verb, ' - ', replace(url,'.xml','')) AS 'API Call', COUNT(*) as 'No. of API Calls', avg(ExecutionTime) as 'Avg. Execution Time', count(distinct AccountId) as 'No. Of Accounts', count(distinct ParentAccountId) as 'No. Of Parents' FROM ApiLog WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' GROUP BY CONCAT(verb, ' - ', replace(url,'.xml','')) HAVING COUNT(*) >= 1G<br>*************************** 1. row ***************************<br> id: 1<br> select_type: SIMPLE<br> table: ApiLog<br> partitions: NULL<br> type: ALL<br>possible_keys: ts<br> key: NULL<br> key_len: NULL<br> ref: NULL<br> rows: 22255292<br> filtered: 50.00<br> Extra: Using where; Using filesort<br>1 row in set, 1 warning (0.00 sec) |
The reason for that is simple: the number of rows matching the filter condition was too large for an index scan to be efficient (or at least the optimizer thinks that):
|
1 |
mysql> select count(*) from ApiLog WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' ;<br>+----------+<br>| count(*) |<br>+----------+<br>| 7948800 |<br>+----------+<br>1 row in set (2.68 sec) |
Total number of rows: 21998514. The query needs to scan 36% of the total rows (7948800 / 21998514).
In this case, we have a number of approaches:
However, if we look closer at the “GROUP BY” part of the query, we quickly realize that none of those solutions will work. Here is our GROUP BY part:
|
1 |
GROUP BY CONCAT(verb, ' - ', replace(url,'.xml',''))<br> |
There are two problems here:
Here, I’m trying to add a full index on the URL with innodb_large_prefix=1:
|
1 |
mysql> alter table ApiLog add key verb_url(verb, url);<br>ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes |
Well, changing the “GROUP BY CONCAT(verb, ‘ – ‘, replace(url,’.xml’,”))” to “GROUP BY verb, url” could help (assuming that we somehow trim the field definition from varchar(3000) to something smaller, which may or may not be possible). However, it will change the results as it will not remove the .xml extension from the URL field.
The good news is that in MySQL 5.7 we have virtual columns. So we can create a virtual column on top of “CONCAT(verb, ‘ – ‘, replace(url,’.xml’,”))”. The best part: we do not have to perform a GROUP BY with the full string (potentially > 3000 bytes). We can use an MD5 hash (or longer hashes, i.e., sha1/sha2) for the purposes of the GROUP BY.
Here is the solution:
|
1 |
alter table ApiLog add verb_url_hash varbinary(16) GENERATED ALWAYS AS (unhex(md5(CONCAT(verb, ' - ', replace(url,'.xml',''))))) VIRTUAL;<br>alter table ApiLog add key (verb_url_hash);<br> |
So what we did here is:
Now we can change the query and GROUP BY verb_url_hash column:
|
1 |
mysql> explain SELECT CONCAT(verb, ' - ', replace(url,'.xml','')) <br>AS 'API Call', COUNT(*) as 'No. of API Calls', <br>avg(ExecutionTime) as 'Avg. Execution Time', <br>count(distinct AccountId) as 'No. Of Accounts', <br>count(distinct ParentAccountId) as 'No. Of Parents' <br>FROM ApiLog <br>WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' <br>GROUP BY verb_url_hash <br>HAVING COUNT(*) >= 1;<br><br>ERROR 1055 (42000): Expression #1 of SELECT list is not in <br>GROUP BY clause and contains nonaggregated column 'ApiLog.ApiLog.Verb' <br>which is not functionally dependent on columns in GROUP BY clause; <br>this is incompatible with sql_mode=only_full_group_by |
MySQL 5.7 has a strict mode enabled by default, which we can change for that query only.
Now the explain plan looks much better:
|
1 |
mysql> select @@sql_mode;<br>+-------------------------------------------------------------------------------------------------------------------------------------------+<br>| @@sql_mode |<br>+-------------------------------------------------------------------------------------------------------------------------------------------+<br>| ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |<br>+-------------------------------------------------------------------------------------------------------------------------------------------+<br>1 row in set (0.00 sec)<br><br>mysql> set sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';<br>Query OK, 0 rows affected (0.00 sec)<br><br>mysql> explain SELECT CONCAT(verb, ' - ', replace(url,'.xml','')) AS 'API Call', COUNT(*) as 'No. of API Calls', avg(ExecutionTime) as 'Avg. Execution Time', count(distinct AccountId) as 'No. Of Accounts', count(distinct ParentAccountId) as 'No. Of Parents' FROM ApiLog WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' GROUP BY verb_url_hash HAVING COUNT(*) >= 1G<br>*************************** 1. row ***************************<br> id: 1<br> select_type: SIMPLE<br> table: ApiLog<br> partitions: NULL<br> type: index<br>possible_keys: ts,verb_url_hash<br> key: verb_url_hash<br> key_len: 19<br> ref: NULL<br> rows: 22008891<br> filtered: 50.00<br> Extra: Using where<br>1 row in set, 1 warning (0.00 sec) |
MySQL will avoid any sorting, which is much faster. It will still have to eventually scan all the table in the order of the index. The response time is significantly better: ~38 seconds as opposed to > an hour.
Now we can attempt to do a covered index, which will be quite large:
|
1 |
mysql> alter table ApiLog add key covered_index (`verb_url_hash`,`ts`,`ExecutionTime`,`AccountId`,`ParentAccountId`, verb, url);<br>Query OK, 0 rows affected (1 min 29.71 sec)<br>Records: 0 Duplicates: 0 Warnings: 0<br> |
We had to add a “verb” and “url”, so beforehand I had to remove the COLLATE utf8mb4_unicode_ci from the table definition. Now explain shows that we’re using the index:
|
1 |
mysql> explain SELECT CONCAT(verb, ' - ', replace(url,'.xml','')) AS 'API Call', COUNT(*) as 'No. of API Calls', AVG(ExecutionTime) as 'Avg. Execution Time', COUNT(distinct AccountId) as 'No. Of Accounts', COUNT(distinct ParentAccountId) as 'No. Of Parents' FROM ApiLog WHERE ts between '2017-10-01 00:00:00' and '2017-12-31 23:59:59' GROUP BY verb_url_hash HAVING COUNT(*) >= 1G<br>*************************** 1. row ***************************<br> id: 1<br> select_type: SIMPLE<br> table: ApiLog<br> partitions: NULL<br> type: index<br>possible_keys: ts,verb_url_hash,covered_index<br> key: covered_index<br> key_len: 3057<br> ref: NULL<br> rows: 22382136<br> filtered: 50.00<br> Extra: Using where; Using index<br>1 row in set, 1 warning (0.00 sec) |
The response time dropped to ~12 seconds! However, the index size is significantly larger compared to just verb_url_hash (16 bytes per record).
MySQL 5.7 generated columns provide a valuable way to improve query performance. If you have an interesting case, please share in the comments.
Learn more about Percona Server for MySQL