http://m.habrahabr.ru/post/30046/

PostgresSQL: how to count number of rows returned by a query and do it fast