Understanding Query Flow

You can think about query flow in four different ways. The first is to imagine the query using a logical flow. Some developers, on the other hand, think through a query visually using the layout of SQL Server Management Studio's Query Designer. The third approach is to syntactically view the query . You can view the query in a specific fixed order: SELECTFROMWHEREGROUP BYHAVINGORDER BY. Finally, to illustrate the declarative nature of SQL, the fourth way to think about the query flow — the actual physical execution of the query — is to execute in the most efficient order depending on the data mix and the available indexes.

Syntactical Flow of the Query Statement

In its basic form, the SELECT statement tells SQL Server what data to retrieve, including which columns, rows, and tables to pull from, and how to sort the data. The order of the clauses in the SELECT statement are significant; however, they process in an order different from how they are syntactically specified, which this chapter discusses later.

Following is an abbreviated syntax for the SELECT command:

 [DISTINCT][TOP (n)] *, columns, or expressions
 [FROM data source(s)]
  [JOIN data source
   ON condition](may include multiple joins)
 [WHERE conditions]
 [GROUP BY columns]
 [HAVING conditions]
 [ORDER BY Columns];

The SELECT statement begins with a list of columns or expressions. You need at least one expression — everything else is optional. An integer, scalar function, or a string ...

Get Microsoft SQL Server 2012 Bible now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.