Prepared Statements

Often you’ll hear people say you should use prepared statements to avoid sql injection issues. They’re not wrong. But there can be other reasons to use them.

In some db’s when you create a prepared statement and use it over & over you can avoid a fair amount of a speed hit.

When you initially create a prepared statement many db engines will actually do some work to figure out what the optimal mechanism, or query plan, is to access the data in a table.

And by reusing this over & over you can avoid that computation to determine that optimal query plan.

Not ALL db’s do this, and in some it wont matter if you use a prepared statement because they simply recompute the query plan every time anyways.

But, even if the db engine DOES recompute the query plan over & over you still get all the benefits of avoiding sql injections issues by using them.

I’d say they definitely fall into the category of “best practice”.