title: PostgreSQL count number of times substring occurs in text
body: <p>I'm writing a PostgreSQL function to count the number of times a particular text substring occurs in another piece of text. For example, calling count('foobarbaz', 'ba') should return 2.</p>
  
  <p>I understand that to test whether the substring occurs, I use a condition similar to the below:</p>
  
  <pre><code>    WHERE 'foobarbaz' like '%ba%'
  </code></pre>
  
  <p>However, I need it to return 2 for the number of times 'ba' occurs. How can I proceed?</p>
  
  <p>Thanks in advance for your help.</p>