Refactor database query