title: Counter cache column in PostgreSQL
body: <p>In my database I have <code>tasks</code> and <code>comments</code> tables. Each task has many comments.</p>
  
  <p>I'd like to create <code>tasks.comments_count</code> column that would be updated automatically by PostgreSQL, so I can get <code>comments_count</code> (and sort / filter by it) in O(1) time while selecting all tasks.</p>
  
  <p>I know there are language-specific solutions like <a href="http://railscasts.com/episodes/23-counter-cache-column" rel="noreferrer">counter cache</a> of ActiveRecord, but I don't want to use them (I find them fragile). I'd like PostgreSQL to take care of such counter caches.</p>
  
  <p>I also know PostgreSQL supports triggers, but they are hard to write and use (not a solid solution)</p>
  
  <p>Ideally it would be a PostgreSQL extension or some native feature I'm not aware of.</p>
  
  <p>Lazy calculation of such counters would be a great bonus.</p>