Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

UPDATE: I think Postgres incorrectly choose execution plan for queries. As you can see estimation of query execution significantly differs from real execution. Also this queries are performed with different performance on different Postgres versions. For example, for 9.1.13 it takes 1.6s for both queries. For 9.3.4 they both are performed for 280s. Also it's possible to increase performance if turn off enable_nestloop, enable_hashjoin (so query will be performed with another plans). So finally i decided to simplify query.