Execution order of where, group by, having, order by in mysql

These keywords in mysql are executed in the following order: Where, Group By, Having, Order by.

First, where deletes the records that do not meet the conditions in the most original records (so the records that do not meet the conditions should be filtered out in the where statement as much as possible, which can reduce the number of groupings)

Then the filtered views are grouped by the grouping conditions specified after the Group By keyword 

Then the system filters out the records that do not meet the conditions after the grouped view according to the filter conditions specified after the Having keyword.

Finally, the views are sorted according to the Order By statement, so that the final result is produced.


The having clause allows us to filter various data after grouping, and the where clause filters the records before aggregation, which means that it acts before the group by and having clauses. The having clause filters group records after aggregation.

Having can use aggregate functions, such as having sum(money) > 1000

All fields that appear after group by must appear after select at the same time; 

All fields that appear after select but not in the aggregate function must appear after group by at the same time.

The having clause is restricted to columns and aggregate expressions that have been defined in the SELECT statement.

SELECT user_type,is_admin ,SUM(id) FROM saut_m_user
WHERE id > 100
GROUP BY user_type,is_admin
HAVING SUM(status) < 500
ORDER BY is_admin ASC


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325886495&siteId=291194637