Fixed small logic error in SQL