[Solved] Sql Server Optimize left Join

EverSQL Database Performance Knowledge Base

Sql Server Optimize left Join

Database type:

Hello i've these 2 tables :

Table Contac_Group
ID       int
Grp_ID   int
Grp_Name nvarchar(80)
Is_Grp_Hidden  Bit

Table Contacts 
ID     int
Contact_Grp_ID  int /* this values is from Contact_Group Grp_ID */
Contact_Name nvarchar(80)
Contact_Email nvarchar(15)

and this's the Join query i use :

SELECT 
       a.Contact_Grp_ID
      ,a.Contact_Name
      FROM (
    SELECT 
          Contact_Grp_ID
          ,Contact_Name
    FROM Cnts.dbo.[Contacts]
    GROUP BY Contact_Grp_ID,Contact_Name
) a
LEFT JOIN (
    SELECT 
           Grp_ID
          ,Grp_Name
          ,Is_Grp_Hidden
    FROM Cnts.dbo.[Contac_Group]
    where Is_Grp_Hidden =0
    GROUP BY Grp_ID,Grp_Name,Is_Grp_Hidden

) b ON a.Contact_Grp_ID = b.Grp_ID;

So in case i've million of Contacts Data how this inner join can be optimized ?

thank you

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. Avoid Subqueries (query line: 5): 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.
  2. 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.
  3. Remove Redundant Left Joins (modified query below): Redundant LEFT JOINs (e.g. `b`) were detected in the query. Removing them will result in a performance improvement. In some cases, JOINs become redundant after an optimization is applied, such as when converting OR conditions to a UNION clause.
Optimal indexes for this query:
CREATE INDEX contacts_idx_contact_id_contact_name ON Cnts.dbo.Contacts (Contact_Grp_ID,Contact_Name);
The optimized query:
SELECT
        a.Contact_Grp_ID,
        a.Contact_Name 
    FROM
        (SELECT
            Cnts.dbo.[Contacts].Contact_Grp_ID,
            Cnts.dbo.[Contacts].Contact_Name 
        FROM
            Cnts.dbo.[Contacts] 
        GROUP BY
            Cnts.dbo.[Contacts].Contact_Grp_ID,
            Cnts.dbo.[Contacts].Contact_Name) a

Related Articles



* original question posted on StackOverflow here.