[Solved] Improve performing SQL / JOIN

EverSQL Database Performance Knowledge Base

Improve performing SQL / JOIN

I have 2 tables

TABLE1 listing all test questions before test.

TABLE 1:

testid  qnid    qn
1       1       currency of iran
1       2       highest peak        
1       3       longest bridge

TABLE 2 listing test responses as status after test for all students :

TABLE 2:

studentid   testid  qnid    status  

    1       1       1       unanswered      
    1       1       2       unanswered  
    2       1       1       unanswered  
    2       1       2       answered    

The TABLE 2 given is incomplete as it does not contain response for all qnid.

The RESULT should be table listing all testid, qnid from TABLE 1 of test with studentid,status from TABLE 2 for the matching testid,qnid for studentid=2

i.e. RESULT:

testid  qnid    studentid    status     
1       1       2           unanswered
1       2       2           answered
1       3       

TABLE 2 does not contain value for testid=1 qnid=3 from TABLE 1 so its space should be left empty in RESULT table.

The query I used:

select distinct table1.testid,table1.qnid,table2.status 
from table1 
  left outer join table2 
    on table1.testid = table2.testid 
where (table2.studentid = 2 
or table2.studentid =NULL)

But instead the output is:

testid  qnid    status
1       1       unanswered
1       1       answered
1       2       unanswered
1       2       answered
1       3       unanswered
1       3       answered

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.
  2. Prefer IN Clause Over OR Conditions (modified query below): Using an IN clause is far more efficient than OR conditions, when comparing a column to more than one optional values. When using an IN clause, the database sorts the list of values and uses a quick binary search.
Optimal indexes for this query:
ALTER TABLE `table2` ADD INDEX `table2_idx_testid_studentid` (`testid`,`studentid`);
The optimized query:
SELECT
        DISTINCT table1.testid,
        table1.qnid,
        table2.status 
    FROM
        table1 
    LEFT OUTER JOIN
        table2 
            ON table1.testid = table2.testid 
    WHERE
        (
            table2.studentid IN (
                2, NULL
            )
        )

Related Articles



* original question posted on StackOverflow here.