MySQL Stored Procedures

Here is a tip you can use when writing a stored procedure, and using prepared statements.

Since you have to pass the statements in through EXECUTE stmt USING ...   it can get confusing if there are a large number of parameters.

I had this happen recently when I had about 40 parameters in one query.

Although you can pass the same parameter multiple times,  like this:

I did something that would allow me to easily match up the parameters with the lines they go with in the stored procedure.

Here’s a snippet as an example:

I copied the code to another editor, and added line numbers. I could have left them in the stored procedure but chose not to in order to keep it clean.

Then, I was able to make sure that the variables were in the right places by naming them the same way:

Also, notice how I group them together, leaving a space at each place where there is a new line.

You could do the spacing and grouping trick and not use line numbers too, since you can reuse variables in the list, but I prefer this because it is very explicit and clear.

SQL EXPLAIN: The “Extra” column

This column contains additional information about how MySql resolved the query. There is a line in the manual which states:

If you want to make your queries as fast as possible, look out for Extra values of Using filesort and Using temporary.

Let’s examine why those two are bad.

  • Using filesort

If you see this, it means that an extra pass has been made through the data, in order to sort it. This is not as efficient, and indicates that you may be able to improve query performance.

  • Using temporary

This means that a temporary table will have to be created to hold the result. The manual states that this typically happens if the query contains GROUP BY and ORDER BY clauses that list columns differently.

The MySQL Manual has a fascinating page about ORDER BY Optimization.