lundi 3 août 2015

Should I put this filtering in SQL or my application code?

Assume I have the following models in my web Application:

Table User:
   (attr1, attr2, attr3, ...)
Table Prize:
   (condition1, condition2, condition3, prize_val)

The application logic is: if a user satisfies all the conditions of a Prize, I want to grant him the prize. The condition could either be NULL (True for all users) or a specific value. Every condition can be computed with the user attributes. I can do the filtering in 2 ways:

  1. Get all the prize rules from database (at most 100), and iterate the rules in my application code, checking if the current user satisfies the rule, to get a prize list.
  2. User SQL to do the filtering like this:

    SELECT prize from Prize where (condition1=NULL or condition1=user_condition1) and (condition2=NULL or condition2=user_condition2) ...

My question is: which one is more efficient?

And a more general question is: when is it better to do filtering in application code, instead of SQL?

PS. The reason I even think about iterations in code is this: If I iterate in code, and condition1 is NULL for a prize, I don't need to compute the condition1 value for the user (this computation can be expensive); But If I take the SQL approach, I have to pre-compute every condition value for the user.




Aucun commentaire:

Enregistrer un commentaire