title: How GROUP BY and COUNT or SUM works together in SQL queries
body: <p>I wonder how <code>GROUP BY</code> and <code>COUNT</code> or <code>SUM</code> works together in SQL queries.</p>
  
  <p>For example, why does the following code successfully use the <code>SUM</code> function on the rows within each group, not the groups itself?</p>
  
  <pre><code>SELECT 
      product_name,
      SUM(SUBSTRING_INDEX(company_name, '|', -1) LIKE '%live%' AS count_live,
      SUM(SUBSTRING_INDEX(company_name, '|', -1) LIKE '%demo%' AS count_demo,
   SUM(SUBSTRING_INDEX(company_name, '|', -1) NOT LIKE '%live%' AND SUBSTRING_INDEX(company_name, '|', -1) NOT LIKE '%demo%') AS count_other,
   COUNT(*) AS total
  FROM foo GROUP BY product_name ORDER BY total DESC
  ;
  </code></pre>
  
  <p>How it is executed? Which part of this expression executed earlier?</p>