Simplified the SQL query and optimized for processing speed

2 jobs for feature/optimize_sql in 1 minute and 55 seconds (queued for 12 minutes and 18 seconds)