title: SQL speed issue
body: <p>I am using PostgreSQL and want to use a query like this:</p>
  
  <pre><code>SELECT  device, value, id 
  FROM  myTable s 
  WHERE (SELECT  COUNT(*) FROM myTable f WHERE f.id = s.id AND f.value &gt;= s.value ) &lt;= 2
  </code></pre>
  
  <p>This works but the problem is it takes minutes to execute over large data. Is there a faster way that can happen in seconds? What I am trying to do is take only two items from a row where both values are sorted in asc order. </p>
  
  <pre><code>id | device | value
  
  1     123       40
  1     456       30
  1     789       45
  2     12        10
  2     11        9
  </code></pre>
  
  <p>The above is my table (I know ids are not unique, not my design, but it has a purpose) but within the id lets say id = 1, I want to select id, device and value of the smallest 2, so my result would be 1, 123, 30 and 1, 456, 40 and so on for other ids.  </p>
  
  <p>Also, if anyone knows, if you insert sorted data into a database is it a guarantee to read back out in the same order?</p>