Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I explain a query with parameters in MySQL

I have a query

SELECT foo FROM bar WHERE some_column = ?

Can I get a explain plan from MySQL without filling in a value for the parameter?

like image 626
Michael Barker Avatar asked Jun 16 '10 16:06

Michael Barker


People also ask

How do you explain a query?

A query is a request for data or information from a database table or combination of tables. This data may be generated as results returned by Structured Query Language (SQL) or as pictorials, graphs or complex results, e.g., trend analyses from data-mining tools.

What is explain query in MySQL?

The EXPLAIN statement provides information about how MySQL executes statements: EXPLAIN works with SELECT , DELETE , INSERT , REPLACE , and UPDATE statements. When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan.

How do I run an explain plan in MySQL?

To view a visual explain execution plan, execute your query from the SQL editor and then select Execution Plan within the query results tab. The execution plan defaults to Visual Explain , but it also includes a Tabular Explain view that is similar to what you see when executing EXPLAIN in the MySQL client.

How do you optimize MySQL query using explain?

Optimizing Queries with EXPLAIN According to the MySQL documentation, EXPLAIN works alongside SELECT, DELETE, INSERT, REPLACE, and UPDATE statements. It displays information from a built-in MySQL optimizer regarding the statement execution plan and the number of rows scanned in each table.


1 Answers

So long as you're doing only an equals (and not a like, which can have short circuit affects), simply replace it with a value:

EXPLAIN SELECT foo FROM bar WHERE some_column = 'foo';

Since it's not actually executing the query, the results shouldn't differ from the actual. There are some cases where this isn't true (I mentioned LIKE already). Here's an example of the different cases of LIKE:

SELECT * FROM a WHERE a.foo LIKE ?
  1. Param 1 == Foo - Can use an index scan if an index exists.
  2. Param 1 == %Foo - Requires a full table scan, even if an index exists
  3. Param 1 == Foo% - May use an index scan, depending on the cardinality of the index and other factors

If you're joining, and the where clause yields to an impossible combination (and hence it will short circuit). For example:

SELECT * FROM a JOIN b ON a.id = b.id WHERE a.id = ? AND b.id = ?

If the first and second parameters are the same, it has one execution plan, and if they are different, it will short circuit (and return 0 rows without hitting any data)...

There are others, but those are all I can think of off the top of my head right now...

like image 166
ircmaxell Avatar answered Oct 20 '22 10:10

ircmaxell