The Logical Query Processing Order; T-SQL
The Logical Query Processing Order T-SQL
Today we are going over the T-SQL (Transact-SQL) logical query processing order for a SELECT
statement. I've linked everything I used below.
What is the logical query process?
This is the way that standard SQL defines how a query is processed.
Although this process is the conceptual guideline, SQL sometimes bypasses it during the processing of a query.
Note: There are cases where the processing order may differ. See this article for more information.
Example Query:
(Using Microsoft's AdventureWorks2014 database, so feel free to try it out in a TEST environment.)
SELECT SalesOrderID AS OrderID, COUNT(OrderQty) AS NumberOfOrders
FROM Sales.SalesOrderDetail
WHERE SalesOrderID <= 43696
GROUP BY SalesOrderID
HAVING COUNT (OrderQty) <= 4
ORDER BY SalesOrderID ASC;
GO
• I know it starts with SELECT, but you cannot write in a logical processing order without starting with the SELECT clause.
"You cannot write the query in correct logical order."
- Itzik Ben-Gan
• The AS is optional in the syntax but I used it to make the return look simpler.
• The AS command renames the table or column, with an alias that exists for the duration of
the specific query. Using an alias is very helpful when reporting and you want to make the outcome easier to read/ make more sense in regards to the desired return.
Quick steps to sum up the query (in the logical processing order):
1. A SQL statement that Queries rows FROM SalesOrder ID and OrderQty.
2. Filters only rows WHERE SalesOrderID is equal to or greater than 43696.
3. GROUPs by SalesOrderID.
4. Filters only groups HAVING 4 or more orders.
5. The SELECT returns the result for each group.
6. The ORDER BY sorts the rows in the output by SalesOrderID in ascending order.
This results in a clustered index seek and the results are in the screenshot below;
Results:
In conclusion:
The T-SQL is almost like any other language, with syntax being the equivalent of grammar in spoken languages
(you could probably use this exact sentence to describe all other computer languages as well ). Think about this...
Thanks for reading!
If you like what you’ve read on Techie Chatzz, go ahead and join the mailing list to be notified every time we post techie insight.
Stay tuned techies!
#sqlserver #sqldatabase #funday #funactivities #sql #sqlserver #microsoft #learn #techies #techieshelpingtechies #techiechatzz #technitedwestand #query #mssql #technology #techie4life
References:
• AdventureWorks sample databases:
AdventureWorks sample databases - SQL Server | Microsoft Docs
• Logical Processing Order of the SELECT statement:
SELECT (Transact-SQL) - SQL Server | Microsoft Docs
Comments
Post a Comment