Search code examples
mysqlsql-execution-plansql-functionorder-of-execution

Execution order of functions in MySQL


I am aware that the execution order of MySQL is not fixed. But, I heard it usually goes like this:

  1. FROM, including JOINs
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. DISTINCT
  7. ORDER BY
  8. LIMIT and OFFSET

However, if I run functions like COUNT() for example (like the code below), when does it get to be executed? and how does MySQL decide the subjects that will be calculated with the function (e.g. What to count for COUNT() function)? I am confused about the execution order and the target designation of functions like AVG(), SUM(), MAX(), etc. in MySQL.

SELECT productvendor, count(*)
FROM products
GROUP BY productvendor
HAVING count(*) >= 9;

Solution

  • You sequence is not correct
    select is before GROUP BY

    FROM, including JOINs
    WHERE
    SELECT the row  obtained  by from and where in a temporary area for others 
            operation (and build the column alias)
    DISTINCT
    GROUP BY
    HAVING
    ORDER BY
    LIMIT and OFFSET
    return the final result 
    

    the count and the aggegation function are done on a temporary result with the select column .. this operation produce the result filtered by having