Refactor adn extract SQL query building