Sobes.tech
Senior

Do you have experience optimizing SQL queries? Please provide an example.

sobes.tech AI

Answer from AI

Yes, I have experience optimizing SQL queries. For example, there was a query that took a long time to execute due to missing indexes and inefficient JOINs.

Original query:

SELECT orders.id, customers.name, orders.total
FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE orders.status = 'completed'
AND customers.region = 'Europe';

Optimizations:

  1. Added a composite index on the orders table on (status, customer_id).
  2. Added an index on the region field in the customers table.
  3. Rewrote the query to filter by orders.status first, then perform the JOIN using a subquery:
SELECT o.id, c.name, o.total
FROM (
  SELECT id, customer_id, total
  FROM orders
  WHERE status = 'completed'
) o
JOIN customers c ON o.customer_id = c.id
WHERE c.region = 'Europe';

Result: the execution time was reduced from several seconds to fractions of a second by reducing the data volume at the JOIN stage and utilizing indexes.