This is the second post in the series of posts on ‘How to Write Efficient SQL Queries and Statements’

For our demonstration, we will be working on the AdventureWorksLT17 database which is a fictitious, multinational manufacturing company called ‘Adventure Works Cycles’ used for OLTP (Online Transaction Processing) and Real-Time Analytics.

Logical Query Processing

The most common structure for execution of every query in SQL is as follows

SELECT [Columns to Return]
FROM [Tables to Query]
WHERE [Filter Rows using Predicate]
GROUP BY [Arrange Rows by Groups]
HAVING [Filter Groups using Predicate]
ORDER BY [Sort the Output]

However, the Database Engine in SQL Server processes its code in a unique manner also known as ’Logical Query Processing’. It makes use of virtual tables where the results from previous phase are fed onto the next one. These phases and orders are as follows:

FROM > WHERE > GROUP BY > HAVING > SELECT > ORDER BY

Filtering Using Predicates

The **WHERE** clause specifies the search condition for rows returned by the query. It restricts query results to those that satisfy the condition. Queries without the WHERE clause return every row in the Table.

SELECT CustomerID, FirstName + ‘ ‘ + LastName AS Name
FROM SalesLT.Customer
WHERE MiddleName IS NOT NULL;

#sql-server #sql-queries #sql

Part II: Filters, Aggregations, Joins and Common Queries
1.25 GEEK