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
FROM
clause, along withJOIN
s, sets the base datatable(s) and any joining of tables occurs at this stage. - WHERE: Once we have the base data table, the
WHERE
clause filters this data based on the condition specified. - GROUP BY: After the
WHERE
clause has filtered the data,GROUP BY
will aggregate the data into groups as specified. - HAVING: If the
HAVING
clause is present, it will filter the data after it has been grouped (this is the key difference betweenWHERE
andHAVING
-WHERE
filters before grouping,HAVING
filters after grouping). - SELECT: The
SELECT
clause 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,
DISTINCT
will remove any duplicate rows from the result set specified by theSELECT
clause. - ORDER BY: Finally, the
ORDER BY
clause 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