Article Directory
with as
Overview:
WITH AS:
Is to separate a subquery part, sometimes to improve the readability of the sql statement, sometimes to improve the performance of the sql statement
scenes to be used:
- When there are multiple similar sub-queries, use with as to write the common part.
- Because the results of the subquery are in the memory temporary table, the execution efficiency is higher (the temporary table is automatically cleared by the PGA after the session ends)
Note the situation:
- Generally speaking, if the table name defined by the with as phrase is called 2 or more times, the CBO optimizer will automatically put the data obtained by the with as phrase into the temporary table (corresponding to the execution plan
SYS_TEMP_XXX
). - If it is only called once, it will not.
/ + materialize / optimization
hint keyword | description |
---|---|
/*+ materialize*/ |
The result of the mandatory requirements with as converted into a temporary table |
/*+ inline*/ |
Contrary to the above, no conversion |
Example 1: When the table name defined by the with as phrase is used once
WITH t_emp AS
(SELECT /*+ materialize*/ e.empno, e.ename, e.sal
FROM scott.emp e
WHERE e.sal > (SELECT AVG(e_1.sal) FROM scott.emp e_1))
SELECT * FROM t_emp;
Implementation plan:
Example 2: When the table name defined by the with as phrase is used twice or more
WITH t_emp AS
(SELECT /*+ materialize*/ e.empno, e.ename, e.sal
FROM scott.emp e
WHERE e.sal > (SELECT AVG(e_1.sal) FROM scott.emp e_1))
SELECT * FROM t_emp t WHERE t.empno = '7566'
UNION ALL
SELECT * FROM t_emp t WHERE t.empno = '7698';