neo33 neo33 - 2 months ago 10
SQL Question

How does SQL Server process the following query?

I was making some queries to the database called: Northwind that is available to make proves, if you download it from the official site, I performed the following query:

SELECT C.CategoryName NAME,
P.CATEGORYID CODE,
COUNT(*) 'PIECES',
SUM(UnitPrice*UnitsInStock) 'AMOUNT'
FROM
Northwind.dbo.Categories C, Northwind.dbo.[products] P
WHERE
P.CategoryID = C.CategoryID
AND
P.CategoryID>2
GROUP BY
P.CategoryID, C.CategoryName
HAVING SUM(UnitPrice*UnitsInStock)>10000
ORDER BY 'AMOUNT' DESC;


The query is giving me the right results:

NAME CODE PIECES AMOUNT
--------------- ----------- ----------- ---------------------
Seafood 8 12 13010.35
Dairy Products 4 10 11271.20
Confections 3 13 10392.20


The fact is that I can't figure out, how does SQL Server compute that query, since many operations are involved, In some point SQL Server has to generate a temporary data base to perform the
HAVING
:

HAVING SUM(UnitPrice*UnitsInStock)>10000


I would like to receive an explanation about the order that takes SQL Server to perform the query, I mean what is the first and last operation that SQL Server perform besides I can't figure out how does it know that has to apply the operation called SUM to the table called: products,

SUM(UnitPrice*UnitsInStock) 'AMOUNT'


I am not specifying that however is computing well the operation, also the
COUNT
for me is very ambiguous but is giving me the correct result, I really appreciate any detailed explanation of how does it computes this query, thanks for the support.

Answer

You will have to look at logical order processing of a query by Itzik Ben-Gan ,he dedicated a whole chapter and explained in detail each step..The link is here...

Below are the clauses that may execute in logical order and output of each clause is presented to the clause in next phase..

5 SELECT 5.2 DISTINCT 7 TOP <TOP_spec>
                                  5.1 <select_list>
                              1 FROM <table_operators: JOIN, APPLY, PIVOT, UNPIVOT>
                              2 WHERE <predicate>
                              3 GROUP BY <definition_of_grouping_sets>
                              4 HAVING <predicate>
                              6 ORDER BY <order_by_list>
                              7 OFFSET <offset_spec> FETCH <fetch_spec>