For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
The optimization process and recommendations:
- Avoid Calling Functions With Indexed Columns (query line: 6): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `organization_code` is indexed, the index won’t be used as it’s wrapped with the function `NVL2`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
- Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
- Avoid Subqueries (query line: 6): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
- Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `org_organization_definitions` ADD INDEX `org_definitions_idx_organization_code` (`organization_code`);
The optimized query:
SELECT
*
FROM
org_organization_definitions ORG
WHERE
ORG.organization_code IN NVL2(:p_org_code, (SELECT
REGEXP_SUBSTR(:p_org_code,
'[^,]+',
1,
DUAL.LEVEL)
FROM
DUAL CONNECT
BY
REGEXP_SUBSTR(:p_org_code,
'[^,]+',
1,
DUAL.LEVEL) IS NOT NULL), ORG.organization_code)