Fixing sql query