Query optermization involves improving the performance of SQL queries to ensure they run efficiently. This section will cover various techniques and best practices for optimizing SQL queries, including indexing strategies, query rewriting, and analyzing execution plans.
Optimizing queries can significantly reduce execution time and resource consumption, leading to faster performance and better scalability of your database applications.
The execution plan shows how the SQL database engine executes a query. Understanding and analyzing execution plans can help identify bottlenecks and inefficient operations.
- In DuckDB: Use the
EXPLAINstatement. - In MySQL: Use the
EXPLAINstatement. - In PostgreSQL: Use the
EXPLAINstatement. - In SQL Server: Use the
Display Estimated Execution Planoption.
Example
EXPLAIN SELECT * FROM employees WHERE departmentid = 1;Effective use of indexes can greatly improve query performance.
CREATE INDEX idx_department_id ON employees (departmentid);CREATE INDEX idx_department_name ON employees (departmentid, lastname);Having too many indexes can slow down write operations and increase maintenance overhead.
Avoid using SELECT *; specify only the columns you need.
-- Inefficient
SELECT
*
FROM employees;
-- Efficient
SELECT
firstname,
lastname,
departmentid
FROM employees;Subqueries can be less efficient than joins.
-- Subquery
SELECT
firstname,
lastname
FROM employees
WHERE department_id = (SELECT departmentid FROM departments WHERE departmentname = 'Sales');
-- Join
SELECT
e.firstname,
e.lastname
FROM employees e
JOIN departments d
ON e.departmentid = d.departmentid
WHERE d.departmentname = 'Sales';Filter data as early as possible to reduce the number of rows processed.
-- Inefficient
SELECT
*
FROM employees
ORDER BY lastname
WHERE departmentid = 1;
-- Efficient
SELECT
*
FROM employees
WHERE departmentid = 1
ORDER BY lastname;Joins can be resource-intensive. Use the following strategies to optimize joins:
Inner joins are generally faster than outer joins.
-- Outer Join
SELECT
e.firstname,
d.departmentname
FROM employees e
LEFT JOIN departments d
ON e.departmentid = d.departmentid;
-- Inner Join
SELECT
e.firstname,
d.departmentname
FROM employees e
INNER JOIN departments d
ON e.departmentid = d.departmentid;CREATE INDEX idx_department_id ON employees (departmentid);
CREATE INDEX idx_department_id ON departments (departmentid);Using functions on indexed columns can prevent the use of indexes.
-- Inefficient
SELECT
*
FROM employees
WHERE UPPER(lastname) = 'SMITH';
-- Efficient
SELECT
*
FROM employees
WHERE lastname = 'Smith';Wildcards at the beginning of LIKE patterns can prevent index use.
-- Inefficient
SELECT
*
FROM employees
WHERE lastname LIKE '%mith';
-- Efficient
SELECT
*
FROM employees
WHERE lastname LIKE 'Smi%';- Go back over the
queriesyou have created as part off this course and update these to make them moreefficient. Use theexecution plansandsavethe updated query along side youold version.