title: SQL Server : rewriting WHERE clause based on data in million records table
body: <p>See below query which is taking nearly 10 minutes to run. Can this be rewritten to fetch results faster, mainly the where clause condition...</p>
  
  <p>Number of records:</p>
  
  <ul>
  <li>Table tmp_TimeIntervals: 1440</li>
  <li>Table tmp_Activities: 1299688</li>
  </ul>
  
  <p>Code:</p>
  
  <pre><code>select
      i.ID,
      sl.SPID,
      i.PeriodStart,
      DATEDIFF(mi, i.PeriodStartUTC, sl.ENDTIME)
  from
      tmp_TimeIntervals i 
  join
      tmp_Activities sl on (sl.StartTime &lt;= i.PeriodStartUTC
                            and (sl.Endtime &gt; i.PeriodStartUTC 
                            and sl.Endtime &lt; PeriodEndUTC))
  </code></pre>
  
  <p>Regards</p>