When to use Stored Procedures

Kevin Partner
18 May 2008

Version 5 of MySQL added Stored Procedures and, as is often the case when you've been using earlier versions, I didn't notice at all, until a client asked whether the site I'm building for him should be using this technique for interacting with a database. In this case, the answer is a resounding no since it would add an unnecessary level of complexity to a site in which the MySQL queries rarely involve more than one table at a time.

So, when should they be used?

A Stored Procedure is, as its name suggests, a series of SQL statements saved for use later, sort of like an old fashioned .bat Batch file on steroids. They're particularly useful where you have a complex sequence of actions that never changes: you can get it right once and then run it with much lower overheads in future.

I've also heard claims that Stored Procedures improve security against SQL Injection but it's hard to see why where dynamic data is concerned and, after all, PHP includes mysql_real_escape_string which protects against this form of attack.

So, it seems to me that Stored Procedures would be useful for busy sites with repetitive actions (for example interfacing a shopping cart with a stock management system) but do they have uses for more typical web applications? Or would you suggest that they should be used for every SQL query?

I really don't know where the line should be drawn: at the extremes it's pretty clear but the line is extremely fuzzy. Any thoughts?

Read more about: