简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM