I think this is one the most import concept to master when learning SQL.
Keyed-in order: the syntax order
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
Logical Query Processing (with easy to remember phrase, credit to my co-worker): the order logically query is processed
FROM -- For
WHERE -- Wives
GROUP BY -- Good
HAVING -- Husbands
SELECT -- Sing
ORDER BY -- Often
Logical Query Processing detail
FROM
Operators: CROSS JOIN, INNER JOIN, OUTER JOIN, CROSS APPLY, OUTER APPLY, PIVOT, UNPIVOT
WHERE
GROUP BY
HAVING
SELECT
EXPRESSION
DISTINCT
TOP
ORDER BY
Each phase output is served as input for the next phase
For optimization, SQL Server may process the query in any order.
Different between WHERE and HAVING clause:
WHERE evaluated before rows are grouped.
HAVING evaluated after rows are grouped.
SELECT statement:
All-at-once manner, no left to right
That mean this query will fail
SELECT 2*4 AS x, 2*x AS [2x]; --error invalid column x
ORDER BY
Returns a cursor, result is not a set and not relational
Add cost to query
Credits: Microsoft 70-461 Training Kit
No comments:
Post a Comment