laika222
12/2/2017 - 8:30 PM

Logical Processing, Processing Order of Instructions

/*

SQL doesn't process the instructions in the order that you write them out. Here is how a statement
is written:

5: SELECT <select list>
1: FROM	  <table source>
2: WHERE  <search condition>
3: GROUP BY <group by list>
4: HAVING <search condition>
6. ORDER BY <order by list>

And here is how it is evaluated:

1: FROM	  <table source>
2: WHERE  <search condition>
3: GROUP BY <group by list>
4: HAVING <search condition>
5: SELECT <select list>
6. ORDER BY <order by list>

This is important, as it can inform how you write queries to maximize efficiency. Also, aliases
specified on any tabe will not be visible to any step in the query except the ORDER BY step. An 
alias in the FROM step will not be visible to the WHERE, GROUP BY, or HAVING clauses (you'll need
to use the original name of the column), but you CAN use the alias in the ORDER BY clause (the only
clause happening after the SELECT clause).
*/

SELECT appeal_no AS newappeal
FROM T_APPEAL
WHERE appeal_no > 100 -- alias IS NOT visible, you have to use the original column name
ORDER BY newappeal -- alias IS visible and you can either use alias or original column name

/*

If you are using an INNER JOIN and you use a filtering predicate in the ON clause, SQL Server will 
evaluate the ON clause filter first based on its estimates of the cost in a technique called 
*predicate pushdown*. In other words, predicate pushdown is an optimization that applies conditions 
(predicates) as early as possible — ideally preventing any loading of unneeded rows (filter first, 
then match).

*/