This builds an sql query dynamically