2017-01-16

Logical order of operations in SELECT statements

Lack of implementing of logical order in SELECT statements may force to encounter several obstacles. Elements of this command and writing some queries will be broadly explained in the post. It is needed to look at whole structure of SELECT statement, and understanding each conditions lets us put the command in logical orders, do not force yourself to memorize as formula.



SELECT and FROM elements are mandatory fields in SQL query, it means:



To consolidate the understanding of logical orders let’s check it out: Scenario: Required a task contains to sum the Persons’ data, that has name Rob and modification date of their information. Order by given name only.


Used AdventureWorks2014 database as sample, you can view whole table and subsections throughout Object Explorer window or by writing SELECT ALL formula as shown. You may filter by WHERE clause, i did not.Afterward group them by selected columns in first query,FirstName and ModifiedDate,it lets to sum all selected columns as a cluster under group command. It is time to filter by given name,so quest HAVING element.Finally order by the name.

WHERE clause was not requested,you can filter broadly via applying other columns, not only columns mentioned in GROUP BY query.Note that that is difference between WHERE and HAVING elements.

HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

To sum up, handling the required whole data from source is primary, then by filtering process getting reduced amount of data to work efficiently on, summarize data as group or cluster, filter according to collected information again, and arranging them by specific column names as ascending or descending order.

Order of SELECT statement clauses in SQL:

 FROM WHERE GROUP BY HAVING SELECT ORDER BY 

To get broad explanations check my YouTube video out (in Turkish only).


No comments:

Post a Comment