How a SQL query executes?
SQL (Structured Query Language) is a declarative language which means it tells the SQL engine what to do rather than how to do it.
The order in which SQL executes defines how each clause of query is evaluated. Each SQL query follows a specific order of execution,similar to how mathematical operations follow DMAS rule. Now let’s have a quick look at the SQL query execution order.
FROM/JOIN(s)
These clauses execute first to gather the whole working set of data that is being searched and then rest of the operations are perfomed on it.WHERE
Once the data is gathered, WHERE clause is applied to each record and those records which do not satisfy the condtion are discarded.GROUP BY
When the data is filtered according to WHERE caluse then comes the grouping. GROUP BY caluse groups the records based on common values in the column specified in the GROUP BY clause which results in as many rows as there are unique values in that specified column.HAVING
After GROUP BY, HAVING clause is executed to remove those grouped records that do not satisfy the condition mentioned in HAVING clause.SELECT
In the SELECT clause, all the desired columns or desired data is fetched.ORDER BY
If an ORDER BY clause is specified, the data from the SELECT records is sorted in either ascending or descending order based on specified column(s).
Conclusion
At first glance, this might seem unnecessary or unimportant. If our query is returning the required result, then what’s the point of looking into the fact that how our clauses are being executed or evaluated? The main point is that knowledge of the query execution order becomes very helpful while troubleshooting errors, writing lengthy queries, or writing complex Stored Procedures (SPs).So those looking to troubleshoot errors,building complex queries or SPs with greater ease will surely be at much ease if they have the understanding that how these clauses in SQL are executed.