Fixing bad SQL