Fixing bad sql