refactored sql