Does MySQL eliminate common subexpressions between SELECT and HAVING/GROUP BY clause? How to test it?


To test, use the sleep() function.

Case 1

The syntax is as follows −

SELECT yourColumnName+sleep(yourIntegerValue)
FROM yourTableName
GROUP BY yourColumnName+sleep(yourIntegerValue);;

Case 2 − You can use another syntax which is as follows −

SELECT yourColumnName+sleep(yourIntegerValue) As anyAliasName
FROM yourTableName
GROUP BY yourAliasName;

To understand the above syntaxes, let us create a table. The query to create a table is as follows −

mysql> create table sleepDemo
   -> (
   -> value int
   -> );
Query OK, 0 rows affected (1.25 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into sleepDemo values(40);
Query OK, 1 row affected (0.18 sec)
mysql> insert into sleepDemo values(60);
Query OK, 1 row affected (0.19 sec)
mysql> insert into sleepDemo values(60);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from sleepDemo;

Here is the output −

+-------+
| value |
+-------+
| 40    |
| 60    |
| 60    |
+-------+
3 rows in set (0.00 sec)

Here is the query to eliminate common sub expressions between SELECT and HAVING/GROUP BY clause.

Case 1 − The query is as follows −

mysql> SELECT value+sleep(3)
   -> FROM sleepDemo
   -> GROUP BY value+sleep(3);

The output is as follows −

+----------------+
| value+sleep(3) |
+----------------+
| 40             |
| 60             |
+----------------+
2 rows in set (9.00 sec)

The above query takes 9 seconds for each value (40 for 3 seconds,60 for 3 seconds, 60 for 3 seconds).

Case 2 − The query is as follows −

mysql> SELECT value+sleep(3) As v
   -> FROM sleepDemo
   -> GROUP BY v;

The output is as follows −

+------+
| v    |
+------+
| 40   |
| 60   |
+------+
2 rows in set (9.00 sec)

Updated on: 30-Jul-2019

32 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements