I am not using prepared statements. Postgres documentation and previous questions in the pgsql-performance mailing list mention that the query plan is cached only when prepared statements are used.
In the above thread Tom Lane mentions that the plan is never cached for raw queries. Yet, this is exactly what seems to be happening in my case. Am I missing something?
The query plan itself is not cached, but all the metadata about the (large number) of tables used in the query is cached. Apparently reading/parsing that data is the slow step, not coming up with the actual plan.
> Please let me know how I can make sure the query execution for the first time is fast too.
Don't keep closing and reopening connections. Use a connection pooler (pgbouncer, pgpool, whatever pooler is built into your language/library/driver, etc.) if necessary to accomplish this.