All about Order of Execution in SQL

All about Order of Execution in SQL

The Order of Execution in SQL is as given in the diagram below.

The Sequence of execution of SQL Query is defined below.

1. SELECT Returns or derives the required data.

2. FROM Selects the table from which data is obtained.

3. JOINS Derives common data from a different table.

4. WHERE Applies a condition to filter data.

5. GROUP BY Aggregates the data.

6. HAVING Filters the aggregated data.

Difference between how the query is written and how you should think about it.

Here, the query's steps don't happen in the order they're written. In reality the execution is much more complicated but if we can get a basic understnding of how it executes in the backend.

No one will ask you about how it is executed in the backend but you should it know to process the huge tables in your mind before actually writing the query.

Example -

Select e_id, e_name, 
email, gender
from Employee
where gender ='M'

Here the FROM clause is executed first to determine the table. Then WHERE clause is executed to determine the filter condition. Then SELECT statement is executed to extract the data that satisfies this condition in the table.

AND

You can already see the order of writing the query in the example.

The END - Hope your doubts are cleared now!!

Did you find this article valuable?

Support The Analyst Geek by becoming a sponsor. Any amount is appreciated!