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:
- Added a composite index on the
orderstable on(status, customer_id). - Added an index on the
regionfield in thecustomerstable. - Rewrote the query to filter by
orders.statusfirst, 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.