Fix, check and performance improvement around SQL query