Refactors SQL query