Querying and aggregation
WHERE, AND/OR and logical order
Separate row filters from result expressions.
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.
Use it to turn business rules into explicit, testable predicates.
Mixing AND/OR without parentheses or using a SELECT alias in WHERE.
One topic. Three levels of depth.
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.
Try it yourself first.
Find products in stock priced below 1000.
Show the solution and explanation
SELECT ProductName FROM lab.Product WHERE Stock > 0 AND Price < 1000;Mouse and Notebook match. Cable is cheap but has no stock.