Based on a large number of SQL execution mechanisms and practices, we can optimize SQL statements following certain rules to more quickly execute SQL statements and obtain correct results.
UNION eliminates duplicate rows while merging two result sets but UNION ALL merges the two result sets without deduplication. Therefore, replace UNION with UNION ALL if you are sure that the two result sets do not contain duplicate rows based on the service logic.
If there are many NULL values in the JOIN columns, you can add the filter criterion IS NOT NULL to filter data in advance to improve the JOIN efficiency.
nestloop anti join must be used to implement NOT IN, and Hash anti join is required for NOT EXISTS. If no NULL value exists in the JOIN column, NOT IN is equivalent to NOT EXISTS. Therefore, if you are sure that no NULL value exists, you can convert NOT IN to NOT EXISTS to generate hash join and to improve the query performance.
As shown in the following figure, the t2.d2 column does not contain null values (it is set to NOT NULL) and NOT EXISTS is used for the query.
SELECT * FROM t1 WHERE NOT EXISTS (SELECT * FROM t2 WHERE t1.c1=t2.d2);
The generated execution plan is as follows:
If a plan involving groupAgg and SORT operations generated by the GROUP BY statement is poor in performance, you can set work_mem to a larger value to generate a hashagg plan, which does not require sorting and improves the performance.
The DWS performance greatly deteriorates if a large number of functions are called. In this case, you can modify the pushdown functions to CASE statements.
Using functions or expressions for indexes stops indexing. Instead, it enables scanning on the full table.
You can split an SQL statement into several ones and save the execution result to a temporary table if the SQL statement is too complex to be tuned using the solutions above, including but not limited to the following scenarios:
For details about SQL tuning, see SQL Tuning Overview.