sql query amended
bug fixes