title: SQL Query Optimisation: Comparing Adjacent Rows
body: <p>I currently have the following query that takes a LONG time to execute</p>
  
  <pre><code>SELECT * FROM Table t1
  WHERE EXISTS
  (
      SELECT * FROM Table t2
      WHERE
      (
          t1.Key = t2.Key - 1
          AND t1.Foo = 1
          AND t2.Bar = 0
      )
  )
  </code></pre>
  
  <p>The <code>Key</code> is the primary key field. I am only comparing adjacent rows, so intuitively it seems the quickest implementation would be to compare all pairs of adjacent rows, N-1 say. The way my query works, I think it may be comparing each row with every other row in <code>Table</code>, i.e. taking N*N comparisons.</p>
  
  <p>Is there a better way to write the query?</p>