title: Performance with NOT EXISTS - t-sql query
body: <p>This (modified for simplicity) query is part of a larger query, and joined on date with other selects. However I have pinned this section to be dog slow. Say I have a UserLoginHistory-table that logs each login for a user. For each user I want the date they first logged in. (Later on in the query, I group by LogDate to get how many first-time logins there were each day.)</p>
  
  <pre><code>select
      LogDate, --(this value is only date, no time)
      UserId
  from
      UserLoginHistory ul
  where
      not exists
          (
              select 
                  * 
              from 
                  UserLoginHistory ulPrevious
              where
                  ulPrevious.LogDate &lt; ul.LogDate
                  and ul.UserId = ulPrevious.UserId
          )
  group by ul.LogDate, ul.UserId
  </code></pre>
  
  <p>Obviously the NOT EXISTS-part is the slow one. But I can't figure out how to replace it by something more efficient doing the same job. </p>
  
  <p>With a small UserLogHistory-count, performance is no problem. It's when I get to around 15 000 it starts getting slow. Maybe I should batch the result for each day into another table, but I'd like to find a better solution to this query as there should be one out there...</p>
  
  <p>Thanks for your time!</p>