logical fix for sql query