query (1)
query (1)
Example:
sql
Copy
-- Without Index (Full Scan)
SELECT * FROM Employees WHERE department = 'Sales';
Explanation:
Example:
sql
Copy
-- Bad: Fetches all columns
SELECT * FROM Employees;
Explanation:
sql
Copy
-- Inefficient (Cartesian Product)
SELECT * FROM Employees, Departments;
Explanation:
Example:
sql
Copy
-- Bad: Processes all rows before filtering
SELECT department, AVG(salary)
FROM Employees
GROUP BY department
HAVING department = 'Engineering';
Explanation:
Example:
sql
Copy
-- Subquery (Slower)
SELECT name FROM Employees
WHERE dept_id IN (SELECT id FROM Departments WHERE location = 'NY');
-- JOIN (Faster)
SELECT e.name
FROM Employees e
JOIN Departments d ON e.dept_id = d.id
WHERE d.location = 'NY';
Explanation:
Example:
sql
Copy
-- Bad: Fetches all rows
SELECT * FROM Orders;
Explanation:
Example:
sql
Copy
-- Bad: Index not used due to UPPER()
SELECT * FROM Employees WHERE UPPER(name) = 'JOHN';
Explanation:
Example:
sql
Copy
EXPLAIN SELECT * FROM Employees WHERE salary > 50000;
Output Analysis:
sql
Copy
sql
Copy
3. Query Caching
sql
Copy
5. Conclusion
• Optimized queries run faster and use fewer resources.
• Use indexing, proper joins, and filtering strategies.
• Always check execution plans with EXPLAIN.
Next Steps: