refined the sql query a bit