Below query times out after adding these two lines or any single one of it
AND final IS NOT NULL
ORDER BY tmodified ASC
Query keeps running more then 10 min.... and time out.
if I remove above two lines, it return the results within 1 milliseconds, which works Ok.
Any idea how can I make above two lines work with below query?
Table table_h has 36 million records and in this table
column final is numeric(10,5)
column tmodified is bigint, Timestamp
I am using Postgres 9.4
Here is the complete query.
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 >= 0
AND h.final IS NOT NULL
AND h.tmodified >= 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 >= 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 > 1499903419)