How to use ORDERED Hint to Tune a SQL with subquery for Oracle?

Discussion in 'Oracle' started by Richard To, Nov 12, 2021.

  1. Richard To

    Richard To Member

    Joined:
    Sep 18, 2017
    Messages:
    88
    Likes Received:
    36
    Trophy Points:
    18
    Gender:
    Male
    Here the following is the description of the ORDERED hint.

    The ORDERED hint causes Oracle to join tables in the order in which they appear in the FROM clause.

    If you omit the ORDERED hint from a SQL statement performing a join, then the optimizer chooses the order in which to join the tables. You might want to use the ORDERED hint to specify a join order if you know something about the number of rows selected from each table that the optimizer does not. Such information lets you choose an inner and outer table better than the optimizer could.

    We usually use an ORDERED hint to control the john order, but how this hint causes a SQL with a subquery. Let’s use the following SQL as an example to see how ORDERED hint works for a subquery.

    SELECT *
    FROM DEPARTMENT​
    where dpt_id
    in (select emp_dept from employee
    where emp_id >3300000)​

    Here the following is the query plan of the SQL, it takes 68.84 seconds to finish. The query shows a “TABLE ACCESS FULL” of the DEPARTMENT table and “NESTED LOOPS SEMI” to an “INDEX RANGE SCAN” of EMPLOYEE.
    [​IMG]
    If you think it is not an effective plan, you may want to try to reorder the join path and see if an ORDERED hint is working or not in a subquery case like this:

    SELECT /*+ ORDERED */ *
    FROM department
    WHERE dpt_id IN (SELECT emp_dept
    FROM employee
    WHERE emp_id > 3300000)​

    Here is the query plan of the hinted SQL and the speed is 3.44 seconds which is 20 times better than the original SQL. The new query plan shows the new join order that EMPLOYEE is retrieve first and then hash join DEPARTMENT later. You can see the ORDERED hint will order the subquery’s table first. This new order clauses a new data retrieval method from the EMPLOYEE table, it makes the overall performance much better than the original query plan.

    [​IMG]

    This kind of rewrite can be achieved by Tosska SQL Tuning Expert for Oracle automatically, there are other hints-injection SQL with better performance, but it is not suitable to discuss in this short article, maybe I can discuss later in my blog.
    https://tosska.com/tosska-sql-tuning-expert-pro-tse-pro-for-oracle/

    [​IMG]
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice