[Solved] Nested inline query faster than Equal Join

EverSQL Database Performance Knowledge Base

Nested inline query faster than Equal Join

Assume two tables:

TRANSACTION
Primary Key: REF_NO
Columns:     REF_NO, TXN_DATE, ITEM_CODE, QUANTITY

ITEM
Primary Key: ITEM_CODE
Columns:     ITEM_CODE, ITEM_DESC

Query (1):

SELECT T.REF_NO, T.TXN_DATE, T.ITEM_CODE,
    I.ITEM_DESC,
    T.QUANTITY
FROM TRANSACTION T, ITEM I
WHERE T.ITEM_CODE = I.ITEM_CODE

Query (2):

SELECT T.REF_NO, T.TXN_DATE, T.ITEM_CODE,
    (SELECT ITEM_DESC FROM ITEM WHERE ITEM_CODE = T.ITEM_CODE) AS ITEM_DESC,
    T.QUANTITY
FROM TRANSACTION T

Indices (indexes) are on both tables as necessary.

The above is a very simplified version of the stuff I'm doing, but the concept is the same.

I was told that (1) is more efficient due to indices, and Explain Plan actually suggests that it is. Explain plan for (1) shows index access on both tables. Explain plan for (2) shows index access on ITEM, but full table access on TRANSACTION.

But my dilemma is when I run them on a very large set of data to time the actual performance, (2) is four times faster than (1)! What are the possible reasons for this? Why should I choose (1) over (2)? (We decided to choose (2) over (1).)

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. 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 `ITEM` ADD INDEX `item_idx_item_code` (`ITEM_CODE`);
ALTER TABLE `TRANSACTION` ADD INDEX `transaction_idx_item_code` (`ITEM_CODE`);
The optimized query:
SELECT
        T.REF_NO,
        T.TXN_DATE,
        T.ITEM_CODE,
        I.ITEM_DESC,
        T.QUANTITY 
    FROM
        TRANSACTION T,
        ITEM I 
    WHERE
        T.ITEM_CODE = I.ITEM_CODE

Related Articles



* original question posted on StackOverflow here.