title: Redundant LEFT JOIN - SQL Optimization
body: <p>How do I optimize the following SQL? Some joins are being done unnecessarily two times. </p>
  
  <pre><code>SELECT DISTINCT
      t1.ID,
      t1.FirstName,
      t1.LastName
  
  FROM Table1 t1
  LEFT JOIN Table2 t2
      ON t2.LeadID = t1.ID
  LEFT JOIN Table3 t3
      ON t2.someID = t3.someID
  LEFT JOIN Table4 t4
      ON t4.UserID = t1.AgentID
  LEFT JOIN Table5 t5
      ON t5.ProspectID = t1.ProspectID
  
  WHERE (t1.ID IN (SELECT UserID FROM Users) OR t1.ID IS NULL)
  AND t1.BEID = 100
  AND t1.LastName &lt;&gt; ''
  AND t1.FirstName &lt;&gt; ''
  
  
  UNION
  
  
  SELECT DISTINCT
      t1.ID,
      t1.FirstName,
      t1.LastName
  
  FROM Table1 t1
  LEFT JOIN Table2 t2
      ON t2.LeadID = t1.ID
  LEFT JOIN Table3 t3
      ON t2.someID = t3.someID
  LEFT JOIN Table4 t4
      ON t4.UserID = t1.AgentID
  LEFT JOIN Table5 t5
      ON t5.ProspectID = t1.ProspectID
  LEFT JOIN QueueMap uq
      ON uq.QueueID = t1.agentID  --&lt;--- this is additional JOIN
      AND uq.QueueID IN (SELECT QueueID FROM UserQueues)
      AND t1.LastName &lt;&gt; ''
      AND t1.FirstName &lt;&gt; '
  </code></pre>
  
  <p>The second part of the SQL (after UNION) is almost similar except that I have one additional LEFT JOIN (as marked by arrow). I have tried creating another table replacing common SQL with a table but it didn't work. </p>