Improved counts query to be faster. Added logging of query.