For something like this, I would agree that set_sql is a good approach. There are things databases are pretty good at, and I think this is one of them. Note that if you are going to reference columns from another table in a join, you'll need to add them as TEMP columns in the class with the sql code.