Refactored MySQL code