One very important thing about T-SQL is the way the query operates and in which order the clauses executes.
3. GROUP BY
6. ORDER BY
The first one to execute is the FROM clause which says were the query is going to show information from.
Second, the WHERE clause is used and this is used to filter the result with some expression, for example only take customers with the customer id = 95. This is used to greatly increase the speed of the query.
Third we have the GROUP BY clause which groups the result in the way you choose. When using this clause you must work with the HAVING, SELECT, ORDER BY in groups. That is, you must only have one result row for each group. This must be done or the query will fail.
Then we have the HAVING clause which are used like the were clause but on groups instead of single rows.
The the SELECT clause specify the columns that the user wants to show. It´s important to notice that when using a WHERE clause or another clause that is executed before the SELECT clause – you can not use the aliases created at the SELECT clause because the SELECT clause has not been executed yet.
Then, last is the ORDER BY clause which is used to sort the final result set in ascending or descending order on some column that has been used in the query. If this one is not used, there is not a guaranteed presentation order. This is because a set has no order. This is the only phase were you can refer to the columns in the SELECT clause. It´s also worth pointing out that the result when using the ORDER BY will not produce a table, it will produce a sorted cursor, a non-relational result.