Can you rewrite the query?
💡 Model Answer
To rewrite a query for better performance, first analyze the current execution plan using EXPLAIN or EXPLAIN ANALYZE. Identify expensive operations such as full table scans, nested loops, or large hash joins. Then consider rewriting the query to use more efficient constructs:
- Replace correlated subqueries with JOINs or EXISTS clauses.
- Use Common Table Expressions (CTEs) to materialize intermediate results if the database supports optimization.
- Add appropriate indexes on columns used in JOIN, WHERE, and ORDER BY clauses.
- Avoid SELECT *; specify only needed columns to reduce I/O.
- If the query uses UNION, consider UNION ALL if duplicates are not required.
Example: Instead of
SELECT * FROM orders o WHERE o.customer_id IN (SELECT id FROM customers WHERE region = 'EU');
Rewrite as
SELECT o.* FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.region = 'EU';
This allows the optimizer to use an index on customers.id and customers.region, turning the IN clause into a more efficient join. Complexity typically drops from O(n*m) to O(n log n) or O(n) depending on indexes.
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