Optimized sql query.