Task 4: Optimize the query WHERE DATE(tep.available_from_departure_date) = departureDate. Explain the problem and suggest a solution.
sobes.tech AI
Answer from AI
The problem with the query WHERE DATE(tep.available_from_departure_date) = departureDate is that applying the DATE() function to the available_from_departure_date column prevents the use of an index on this column, forcing the database to perform a full table scan, which significantly reduces performance.
The optimal solution is to rewrite the condition so that the function is not applied to the column, but to the parameter, or to use a date range. For example, if departureDate is a date without time, you can do the following:
WHERE tep.available_from_departure_date >= departureDate
AND tep.available_from_departure_date < departureDate + INTERVAL 1 DAY
This way, the condition checks whether available_from_departure_date falls within the interval from the start of departureDate to the start of the next day, allowing the use of an index on the column and significantly speeding up the query.