饾棫饾椉饾椊 饾煯饾煬 饾棪饾棨饾棢 饾椌饾槀饾棽饾椏饾槅 饾椉饾椊饾榿饾椂饾椇饾椂饾槆饾棶饾榿饾椂饾椉饾椈 饾榿饾棽饾棸饾椀饾椈饾椂饾椌饾槀饾棽饾榾
Here is the list of the top 20 SQL query optimization techniques I found noteworthy:
- Create an index on huge tables (>1.000.000) rows
- Use EXIST() instead of COUNT() to find an element in the table
- SELECT fields instead of using SELECT *
- Avoid Subqueries in WHERE Clause
- Avoid SELECT DISTINCT where possible
- Use WHERE Clause instead of HAVING
- Create joins with INNER JOIN (not WHERE)
- Use LIMIT to sample query results
- Use UNION ALL instead of UNION wherever possible
- Use UNION where instead of WHERE ... or ... query.
- Run your query during off-peak hours
- Avoid using OR in join queries
- Choose GROUP BY over window functions
- Use derived and temporary tables
- Drop the index before loading bulk data
- Use materialized views instead of views
- Avoid != or <> (not equal) operator
- Minimize the number of subqueries
- Use INNER join as little as possible when you can get the same output using LEFT/RIGHT join.
- Frequently try to use temporary sources to retrieve the same dataset.
Do you know what is 饾棨饾槀饾棽饾椏饾槅 饾棦饾椊饾榿饾椂饾椇饾椂饾槆饾棽饾椏? Its primary function is to determine 饾榿饾椀饾棽 饾椇饾椉饾榾饾榿 饾棽饾棾饾棾饾椂饾棸饾椂饾棽饾椈饾榿 饾槃饾棶饾槅 to execute a given SQL query by finding the best execution plan. The query optimizer takes the SQL query as input and analyzes it to determine how best to execute it. The first step is to parse the SQL query and create a syntax tree. The optimizer then analyzes the syntax tree to determine how to run the query.
Next, the optimizer generates 饾棶饾椆饾榿饾棽饾椏饾椈饾棶饾榿饾椂饾槂饾棽 饾棽饾槄饾棽饾棸饾槀饾榿饾椂饾椉饾椈 饾椊饾椆饾棶饾椈饾榾, which are different ways of executing the same query. Each execution plan specifies the order in which the tables should be accessed, the join methods, and any filtering or sorting operations. The optimizer then assigns a 饾棸饾椉饾榾饾榿 to each execution plan based on the number of disk reads and the CPU time required to execute the query.
Finally, the optimizer 饾棸饾椀饾椉饾椉饾榾饾棽饾榾 饾榿饾椀饾棽 饾棽饾槄饾棽饾棸饾槀饾榿饾椂饾椉饾椈 饾椊饾椆饾棶饾椈 with the lowest cost as the optimal execution plan for the query. This plan is then used to execute the query.
Check in the image the 饾椉饾椏饾棻饾棽饾椏 饾椂饾椈 饾槃饾椀饾椂饾棸饾椀 饾棪饾棨饾棢 饾椌饾槀饾棽饾椏饾椂饾棽饾榾 饾椏饾槀饾椈.
