Refactors SQL querries