When a SQL query is run, it doesn’t execute in the order it’s written. Here’s the correct order of execution:
- FROM and JOINs: The
FROMclause, along withJOINs, sets the base datatable(s) and any joining of tables occurs at this stage. - WHERE: Once we have the base data table, the
WHEREclause filters this data based on the condition specified. - GROUP BY: After the
WHEREclause has filtered the data,GROUP BYwill aggregate the data into groups as specified. - HAVING: If the
HAVINGclause is present, it will filter the data after it has been grouped (this is the key difference betweenWHEREandHAVING-WHEREfilters before grouping,HAVINGfilters after grouping). - SELECT: The
SELECTclause is executed next. It determines which columns of the filtered, grouped data will be in the final result set. It’s also where we specify any aggregate functions to be used. - DISTINCT: If specified,
DISTINCTwill remove any duplicate rows from the result set specified by theSELECTclause. - ORDER BY: Finally, the
ORDER BYclause sorts the data based on the columns specified.
Here’s a visual representation:
1. FROM clause
2. WHERE clause
3. GROUP BY clause
4. HAVING clause
5. SELECT clause
6. DISTINCT clause
7. ORDER BY clause
Tags
sql