A Quick Overview of the MySQL DO Statement

In MySQL we can use the DO statement if we want to execute an expression without getting a result set.

DO works in a similar way to the SELECT statement, but without returning a result set like SELECT normally would. DO can also be slightly faster, given it doesn’t return a result set.

This could be useful in stored functions or triggers that don’t allow us to run statements that return a result set.

Syntax

The official syntax goes like this:

DO expr [, expr] ...

So we can pass multiple expressions separated by a comma (just like we can do with SELECT).

Example

Here’s an example of using the DO statement to execute the SLEEP() function:

DO SLEEP(10);

Result:

Query OK, 0 rows affected (10.08 sec)

This resulted in a 10 second pause (well, 10.08 seconds to be precise), before being presented with the usual “Query OK” message that we get when no results are returned.

Now let’s look at what happens when we use a SELECT statement to execute the same statement:

SELECT SLEEP(10);

Result:

+-----------+
| SLEEP(10) |
+-----------+
|         0 |
+-----------+
1 row in set (10.04 sec)

This time we get a result set that contains 0.

Where DO Cannot be Used

We can’t use DO everywhere that we can use SELECT. For example we can’t do the following:

DO * FROM actor;

Result:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM actor' at line 1

In such cases, we’d need to use a different options, such as the SELECT statement or the TABLE statement.