COMPUTER ENGINEER

Blog
SQL Server / T-SQL6 min study
09/ 65

Querying and aggregation

WHERE, AND/OR and logical order

Separate row filters from result expressions.

UnderstandStudy an examplePractise

Understand the concept

WHERE filters source rows before grouping. AND requires both conditions; OR requires at least one. AND takes precedence over OR, so use parentheses to make the business rule explicit. NULL comparisons can yield UNKNOWN, which WHERE rejects.

A simplified logical order is FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and TOP/OFFSET. A SELECT alias is unavailable in WHERE but can be used by ORDER BY. This logical explanation does not force the optimizer to execute physical operators in that sequence.

WHEN TO USE IT

Use it to turn business rules into explicit, testable predicates.

COMMON PITFALL

Mixing AND/OR without parentheses or using a SELECT alias in WHERE.

01 / PRACTICE

One topic. Three levels of depth.

T-SQL / SQL Server 2019+
SELECT ProductName, Price FROM lab.Product WHERE Price >= 1000;

Selects the four products priced at least 1000.

This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.

02 / YOUR TURN

Try it yourself first.

Find products in stock priced below 1000.

Show the solution and explanation
Worked solution
SELECT ProductName FROM lab.Product WHERE Stock > 0 AND Price < 1000;

Mouse and Notebook match. Cable is cheap but has no stock.