I would push as much logic as possible into the SQL. When writing the AND, OR, etc statements, be aware that although in Perl statements are evaluated left to right, there is no such guarantee in SQL. The Query Optimizer can change the order to whatever it figures will be the most efficient. This can lead to some surprises.