title: Postgres 9.4 sql query timeout
body: <p>Below query times out after adding these two lines or any single one of it</p>
  
  <pre><code>AND final IS NOT NULL 
  ORDER BY tmodified ASC
  </code></pre>
  
  <p>Query keeps running more then 10 min.... and time out. </p>
  
  <p>if I remove above two lines, it return the results within 1 milliseconds, which works Ok.</p>
  
  <p>Any idea how can I make above two lines work with below query?</p>
  
  <p>Table table_h has 36 million records and in this table</p>
  
  <pre><code>column final is  numeric(10,5)
  column tmodified is bigint, Timestamp
  </code></pre>
  
  <p>I am using Postgres 9.4</p>
  
  <p>Here is the complete query. </p>
  
  <pre><code>SELECT DISTINCT t.cid, h.a, am.b, u2.c, u.d, h.e, ie.f, im.g FROM table_am as am
    INNER JOIN table_t as t on (t.id = am.id AND t.type = am.type)
    INNER JOIN table_h AS h on h.iid = t.id
    INNER JOIN table_u AS u ON u.id = h.uid
    INNER JOIN table_u AS u2 ON u2.id = h.lu
    INNER JOIN table_im AS im ON im.asid = am.sid
    INNER JOIN table_ie AS ie ON ie.uid = u.uid
    INNER JOIN table_g AS g ON g.id = h.oldid
  WHERE h.final &gt;= 0 
    AND h.final IS NOT NULL
    AND h.tmodified &gt;= 1499903419
    AND ie.p = im.p
    AND h.sr IN ('x', 'y', 'z')
    AND h.id = (SELECT id FROM table_h WHERE oldid = h.oldid AND final &gt;= 0 
                AND final IS NOT NULL -- Issue is here and
                ORDER BY tmodified ASC -- Issue is here
                LIMIT 1)
    AND h.id NOT IN (SELECT id FROM table_m  WHERE tmodified &gt; 1499903419) 
  </code></pre>