I don’t know if this is a dumb question but I have this two doubts maybe you can help me clear out:
If my database and web server are on the same host, is there any relevant benefit on putting my procedures for conditionally selecting (using more than one SQL query) elements from a table in a SQL database procedure instead of just implementing them in a webserver-side script (in my case PHP) method with the rest of the web application code?
Secondly, and maybe even more important: Am I breaking any design rules doing / not doing this?
More specifically, I made a PHP script to select a random row from a table according to a probability density function determined by the number of previous selections of each row, which goes like this:
function acceptation_rejection_method($link,$tablename,$column,$condition="")
{
$max=get_col("max(".$column.")",$tablename,$link,$condition);
$min=get_col("min(".$column.")",$tablename,$link,$condition);
$bar_value=mt_rand($min,$max);
$count=get_nelements($tablename, $link,"where ".$column."<=".$bar_value);
$selected_row=get_row(mt_rand(0,$count-1), $tablename, $link,"where "
.$column."<=".$bar_value);
return $selected_row;
}
My function implements the acceptance rejection method (http://en.wikipedia.org/wiki/Acceptance-rejection_method), and my question is: Taking on account that my database and my web server are on the same host, is it of any improvement to rewrite that script as SQL code returning the row? (Assuming that all users of my app are using it constantly, like almost once in every request)
If I’m interpreting your question correctly, you want to know whether you should encode your acceptance/rejection algorithm into a pure database function, or whether what you’re doing here is “right”, from both an architectural and a performance point of view.
From a performance point of view, if there were a way to represent the query as a single SQL statement, it would likely be faster than your current implementation, but (assuming the column is indexed), probably not all that much faster.
You could, of course, create a stored procedure – but it looks like you’re running this on multiple tables and columns, so you’d end up with lots of stored procedures.
Stored procedures have benefits and drawbacks, but in this case I’d say they make the application more fragile. Again, I doubt whether you’d see a huge performance impact.
Architecturally, I think what you’re doing is likely the cleanest solution – you’re abstracting the algorithm behind a single method.