Select Statement Execution Order In SQL Server

Introduction

We all can write the SELECT Statement in SQL Server. But how many of us know the execution order of SELECT statement query?. In this article, lets discuss how the SELECT statement is Executed or the in which order the Query is executed.

Query Order Of Execution

SELECT column,column1,.... column n
FROM TableName
    JOIN AnotherTable ON TableName.column = AnotherTable.column
    WHERE constraint_expression
    GROUP BY column
    HAVING constraint_expression
    ORDER BY column ASC/DESC
    LIMIT count OFFSET COUNT;

Lets take above SQL SELECT Statement Syntax as an example.

FROM – This is where the source data set defined or prepared. And this is the only dataset that is available for the following clauses.

WHERE – Once it is prepared, the set is moves to WHERE CLAUSE, it applies the Row Filter to eliminate the rows by using predicates. A Predicates are a logical expression that can evaluate either True or False. The rows which do not meet the predicate condition will be eliminated.

GROUP BY – Filter set then moves to GROUP BY. In this, individual rows can be combined into groups based on the GROUPING EXPRESSION. Expressions consist of Symbols that evaluate a value based on their context.

HAVING – After group by the set moves to another filter HAVING CLAUSE. Here we can filter the whole GROUPS from the SET. This is not possible at WHERE since the GROUPS are not yet formed there.

SELECT – In the select we will provided all the list of expression that we are interested

ORDER BY- To sort the result, presentation order (ASC or DESC)

OFFSET – FETCH – To limit the rows that will be returned

For easy understand, please refer the below Image

Fig.1 The Query Order of Execution

Note: The number in the green represents the order of the Query Execution

Conclusion

In this article, we have discussed about the order of query execution. I hope you all found this article much useful. Please share your feedback in the comment section.

Consider reading other SQL articles of Mine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Built with WordPress.com.

Up ↑

%d bloggers like this: