Can you rewrite the query in a more optimized way, removing any inefficient correlated subqueries?
💡 Model Answer
Correlated subqueries are evaluated once per row of the outer query, which can lead to O(n*m) complexity. A common optimization is to replace them with a JOIN or an EXISTS clause. For example, if you have:
SELECT e.id, e.name
FROM employees e
WHERE EXISTS (SELECT 1 FROM sales s WHERE s.emp_id = e.id AND s.amount > 1000);
You can rewrite it as:
SELECT DISTINCT e.id, e.name
FROM employees e
JOIN sales s ON s.emp_id = e.id
WHERE s.amount > 1000;
This turns the per-row subquery into a set-based join, allowing the optimizer to use indexes on sales.emp_id and sales.amount. If the subquery returns a single value, you can also use a scalar subquery with a derived table or a CTE. Additionally, consider using window functions if you need aggregates per group, e.g., ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...). Always analyze the execution plan to ensure indexes are used and the join is efficient. The goal is to reduce the number of times the subquery is executed and to leverage set operations that the database engine can optimize more effectively.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500