In this article, we will learn how MySQL trace queries. For this, we will rely on the OPTIMIZER_TRACE option.
This tracing option is available from MySQL 5.6 if you try to use it in an earlier version it will not work.
First, we will create an Orders table on which we will build the query we are going to trace. The table will have the following structure and content:
CREATE TABLE `orders` ( |
Script 1. Orders table creation
MySQL trace query
MySQL trace a query very easily with OPTIMIZER_TRACE. We only have to activate the option, execute the query, and then consult the content of the table INFORMATION_SCHEMA.OPTIMIZER_TRACE. When we no longer want to trace our queries, we deactivate the option.
We can execute the following query, to activate OPTIMIZER_TRACE option:
SET OPTIMIZER_TRACE="enabled=on"; |
Script 2. Activate OPTIMIZER_TRACE option
Then we execute the query we want to trace:
SELECT * FROM `orders` |
Script 3. Query to retrieve Orders table rows
Result:
Table 1. Orders table content
Now we check the content of the table INFORMATION_SCHEMA.OPTIMIZER_TRACE:
SELECT QUERY, LEFT(TRACE,1000) AS TRACE FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE; |
Script 4. Query to retrieve INFORMATION_SCHEMA.OPTIMIZER_TRACE table content
Result:
Table 2. MySQL trace query
In the previous example, we limit the length of the TRACE column to 1000 characters. But if we want to see the complete content, we can execute the following script:
SELECT QUERY, TRACE AS TRACE FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE; |
Script 5. Query to retrieve the complete TRACE column content
And finally, we can disable the option OPTIMIZER_TRACE with the following query:
SET optimizer_trace="enabled=off"; |
Script 6. Disable OPTIMIZER_TRACE option
0 comments:
Post a Comment