Basic Queries  «Prev  Next»

Lesson 3

SQL WHERE Clause

Often times you will want a query to return only a subset of the data in a table. For example, when searching VirtualBookShelf's catalog for a list of books by a specific author. The SELECT statement's WHERE clause allows you to select only the rows that satisfy a certain condition. A clause further defines a statement; the following statement, with no clause at all, returns every row:
SELECT * FROM Inventory

Adding a WHERE clause, such as WHERE Author = 'Hemingway', further defines the statement to return only the rows where the author equals Hemingway. The following SQL query returns only VirtualBookShelf's books by Hemingway.
SELECT * FROM Inventory WHERE Author = 'Hemingway'

The WHERE clause uses comparison and logical operators to select rows meeting a specified condition. The following walkthrough breaks that statement into its pieces.

This lesson goes a step further than the last one. Lesson 2 wrote a SELECT statement with no filtering at all, every row, every time. This lesson is where that changes: a single equality comparison is only the simplest case a WHERE clause handles, and the rest of this lesson builds up from there, ranges, sets of values, text patterns, and the correct way to filter for a value that's missing entirely, the kind of filtering a real search feature actually needs.

SELECT * FROM Inventory
1) This part of the statement says to select all columns from the Inventory table.

WHERE
2) The WHERE clause is used to select only the rows that meet a condition.

Author = 'Hemingway'
3) Author is the Inventory column that holds a book's author. The condition: the author equals Hemingway.


SELECT * FROM Inventory
WHERE Author = 'Hemingway'
4) The complete statement. It returns all columns from every row in Inventory where the author equals Hemingway.

Comparison and Logical Operators

SQL has several operators that allow a SELECT statement to be very selective about the rows it returns. The following tables list the comparison and logical operators used with SQL.
  • Comparison Operators:
    Comparison Operators
    SymbolFunction
    =Equal
    <>Not equal
    >Greater than
    >=Greater than or equal
    <Less than
    <=Less than or equal
  • Logical Operators
    Logical Operators
    OperatorFunction
    ANDReturns TRUE if all conditions are true
    ORReturns TRUE if one or more conditions are true
    NOTReturns TRUE if the condition is false

The following statement uses the logical operator AND to select rows where the author equals Hemingway and the price is under twenty dollars:
SELECT * FROM Inventory WHERE Author = 'Hemingway' AND
Price < 20.00

Combining AND and OR in the same condition takes a little more care, because SQL evaluates them in a fixed order: NOT first, then AND, then OR. Without parentheses, WHERE Author = 'Hemingway' OR Author = 'Brooks' AND Price < 20.00 evaluates the AND first, which can return rows that weren't intended. Wrapping the OR condition in parentheses, WHERE (Author = 'Hemingway' OR Author = 'Brooks') AND Price < 20.00, makes the intended grouping explicit instead of relying on SQL Server's default order.

NOT reverses a condition's result: a row that would normally be excluded is included, and a row that would normally be included is excluded. The following statement finds every book that isn't by Hemingway.
SELECT Title, Author FROM Inventory
WHERE NOT Author = 'Hemingway'
This reads naturally as "where author is not Hemingway," and it behaves the same as WHERE Author <> 'Hemingway'. NOT becomes more useful once it's applied to a more complex condition than a single comparison, reversing the result of an entire parenthesized expression at once rather than only a single comparison.

Filtering on a Range, a Set, and a Pattern

A single equality comparison and a basic AND cover a lot of ground, but three more comparison techniques come up often enough to be worth learning here rather than discovering later: filtering on a range of values, filtering on a set of specific values, and filtering on a text pattern.

BETWEEN filters a column to a range, inclusive of both endpoints. The following statement finds every book priced between ten and twenty dollars.
SELECT Title, Author, Price FROM Inventory
WHERE Price BETWEEN 10.00 AND 20.00
This is equivalent to writing WHERE Price >= 10.00 AND Price <= 20.00, but it reads more clearly once a condition involves a range rather than a single boundary.

IN filters a column against a list of acceptable values, replacing a long chain of OR conditions on the same column. The following statement returns books by any of three specific authors.
SELECT Title, Author FROM Inventory
WHERE Author IN ('Hemingway', 'Brooks', 'Fenton')
Written without IN, this would require WHERE Author = 'Hemingway' OR Author = 'Brooks' OR Author = 'Fenton', three repetitions of the same column name for what IN expresses in a single list.

LIKE filters a text column against a pattern rather than an exact value, using the percent sign ( % ) to match any number of characters and the underscore ( _ ) to match exactly one character. The following statement finds every book whose title begins with the word "The".
SELECT Title, Author FROM Inventory
WHERE Title LIKE 'The%'
A pattern like '%Shuttle%' would instead match any title containing the word "Shuttle" anywhere in it, not just at the beginning. LIKE is the right tool for this kind of partial, pattern-based match; the plain equality operator only ever matches a complete, exact value.

The underscore matches exactly one character rather than any number of them, which is useful when a pattern's length is known but one character isn't. WHERE ISBN LIKE '978-0-13-_____-_' would match any ISBN with that exact structure, any digit filling each underscore, rejecting one that's a character too short or too long. Both BETWEEN and IN can also be reversed with NOT, the same way a plain comparison can: WHERE Price NOT BETWEEN 10.00 AND 20.00 finds books outside that range, and WHERE Author NOT IN ('Hemingway', 'Brooks', 'Fenton') finds books by anyone else.

Filtering Rows That Have No Value At All

Module 3, Lesson 2 pointed out that VirtualBookShelf's Customer table allows a missing Phone value, and that comparing a column to NULL with an ordinary equals sign doesn't behave the way comparing it to a real value does. This is where that detail gets resolved.

SQL Server evaluates every WHERE condition to one of three outcomes, not two: TRUE, FALSE, or UNKNOWN. A comparison involving NULL always evaluates to UNKNOWN, and a WHERE clause only keeps rows where the condition is TRUE, never UNKNOWN. That's why WHERE Phone = NULL doesn't work: it doesn't error, it simply never matches anything, no matter how many rows actually have a missing phone number. SQL Server provides two dedicated keywords instead:
SELECT CustomerID, FirstName, LastName
FROM Customer
WHERE Phone IS NULL
SELECT CustomerID, FirstName, LastName, Phone
FROM Customer
WHERE Phone IS NOT NULL
The first finds every customer with no phone number on file; the second finds every customer who has provided one. Neither statement uses the equals sign at all, because IS NULL and IS NOT NULL are their own, separate comparison operators, built specifically to handle the case an ordinary = can't.

SQL Server 2025 also supports a related, newer predicate, IS [NOT] DISTINCT FROM, for comparing two values that might both be NULL and treating that case as equal rather than UNKNOWN. This matters for a parameterized search, the kind Lesson 1 named as this module's second objective, where a search parameter itself might be NULL, meaning "don't filter on this column at all."
DECLARE @SearchPhone nvarchar(20) = NULL;

SELECT CustomerID, FirstName, LastName, Phone
FROM Customer
WHERE Phone IS NOT DISTINCT FROM @SearchPhone
With @SearchPhone left NULL, this statement correctly matches every customer whose Phone is also NULL, something WHERE Phone = @SearchPhone could never do, since comparing two NULLs with = still evaluates to UNKNOWN, not TRUE.

A related function, COALESCE, comes up often alongside NULL filtering, though it solves a different problem: displaying a value instead of a missing one, rather than filtering on whether one is missing. SELECT FirstName, LastName, COALESCE(Phone, 'Not provided') AS Phone FROM Customer; returns the literal text "Not provided" in place of NULL for any customer who hasn't given a phone number, which can be more useful to show on a results page than a blank cell. It's worth knowing this exists, even though filtering with IS NULL and displaying with COALESCE are two separate techniques for two separate jobs, filtering decides which rows come back, display decides how a missing value looks once they do.

The Same Filter, Three Ways

Module 2's conclusion page compared a plain SELECT across raw SQL, ADO.NET, and Entity Framework Core. A WHERE clause makes that same comparison more interesting, because this is where Lesson 1's warning about parameterized queries becomes concrete rather than theoretical. Here's the Hemingway search again, written three ways.
-- Raw SQL, typed directly in Azure Data Studio
SELECT Title, Author, Price FROM Inventory WHERE Author = 'Hemingway';
// ADO.NET, parameterized rather than concatenated
using var cmd = new SqlCommand(
    "SELECT Title, Author, Price FROM Inventory WHERE Author = @Author;", connection);
cmd.Parameters.AddWithValue("@Author", authorName);
using var reader = cmd.ExecuteReader();
// Entity Framework Core
var books = context.Inventory
    .Where(b => b.Author == authorName)
    .ToList();
Notice the ADO.NET version doesn't paste authorName directly into the SQL text; it sends @Author as a placeholder and supplies the actual value separately through Parameters.AddWithValue. That's exactly the parameterized search Lesson 1 described, and it's exactly what stands between a WHERE clause built from user input and the SQL injection vulnerability that same lesson warned about. The EF Core version parameterizes automatically underneath; writing the raw SQL and the ADO.NET version by hand, the way this lesson does, is what makes that automatic behavior something understood rather than taken on faith.

Running These Statements Yourself

Every statement in this lesson runs the same way Lesson 2's did: open Azure Data Studio, connect to VirtualBookShelf's SQL Server 2025 database, open a query window, and type the statement. The only new thing to watch for is the result set itself, which now reflects the WHERE clause's filtering rather than every row in the table. Running SELECT * FROM Inventory; and then SELECT * FROM Inventory WHERE Author = 'Hemingway'; back to back in the same query window is a quick, direct way to see the filter's effect: fewer rows come back the second time, and only rows matching the condition appear at all.

A Few Common Questions

Does the WHERE clause run before or after the columns in the SELECT list are chosen? Before. SQL Server processes a statement's clauses in a fixed logical order: it locates the table named in FROM, filters its rows using WHERE, and only then applies the column list in SELECT to whatever rows survived the filter. This is why a WHERE clause can reference a column that doesn't appear in the SELECT list at all, filtering and projecting are two separate steps.

Can BETWEEN, IN, and LIKE all be combined with AND and OR in the same statement? Yes. Each of them produces a condition that evaluates to TRUE, FALSE, or UNKNOWN, exactly like a plain comparison operator, so they combine with AND, OR, and NOT the same way: WHERE Price BETWEEN 10.00 AND 20.00 AND Title LIKE 'The%' is a perfectly valid statement.

Does SQL Server 2025 support filtering on anything beyond what this lesson covers? Yes, considerably more. SQL Server 2025 can filter rows inside native JSON columns and filter by semantic similarity against vector columns used for AI-driven search, well beyond ranges, sets, and patterns. VirtualBookShelf's schema doesn't have a JSON or vector column, so none of that is needed to filter Inventory or Customer, and this lesson stays with the comparison, logical, range, set, pattern, and NULL-handling techniques that cover ordinary relational data.

Is there a performance cost to writing a WHERE clause one way versus another? There can be, once a table grows large. Wrapping an indexed column in a function, WHERE UPPER(LastName) = 'HENRY', for instance, can force SQL Server to check every row individually rather than using an index to jump straight to matching rows. Writing the comparison directly against the column, without a function wrapped around it, keeps that option open. This isn't noticeable yet with VirtualBookShelf's small Customer and Inventory tables, but it's a habit worth starting now.

Why does the ADO.NET example use a parameter instead of building the SQL text with string concatenation? Because concatenating user input directly into a statement's text reopens the SQL injection vulnerability Lesson 1 described. If a search field accepted an author name and that value were pasted straight into the statement, "WHERE Author = '" + authorName + "'", a crafted input could change what the statement actually does, not just what it searches for. A parameter keeps the statement's structure fixed and sends the value separately, which closes that door entirely, regardless of what the value itself contains.

Can a WHERE clause filter on more than one table's columns at once? Not yet in this course. Filtering across more than one table at a time requires joining the tables together first, a topic this course hasn't introduced. Every example in this lesson filters a single table, Inventory or Customer, which matches this lesson's own objective and everything built so far.

Does a WHERE clause work the same way with INSERT, UPDATE, and DELETE as it does with SELECT? Yes, in the sense that matters most. WHERE's job is always the same: decide which rows a statement applies to, using the exact comparison, logical, range, set, pattern, and NULL-handling techniques covered in this lesson. A SELECT with a WHERE clause decides which rows to return; an UPDATE or DELETE with the same WHERE clause decides which rows to change or remove instead. The clause itself doesn't change; what the statement does with the matching rows does.

What's Ahead

This lesson moved past a single equality comparison into a fuller set of WHERE-clause techniques: combining conditions with AND, OR, and NOT, filtering on a range with BETWEEN, filtering on a set of values with IN, filtering on a pattern with LIKE, and filtering correctly for missing values with IS NULL, IS NOT NULL, and IS NOT DISTINCT FROM. That's a genuine step up from Lesson 2's unfiltered SELECT, and every one of these techniques was shown against VirtualBookShelf's actual Customer and Inventory tables rather than a hypothetical schema.

In the next lesson, the ORDER BY clause to sort rows in a table will be discussed, taking every statement built here and adding control over the order the matching rows come back in. A filtered, sorted SELECT, WHERE narrowing the rows and ORDER BY controlling their order, is close to the shape a real search feature on VirtualBookShelf's own pages would actually need.

After that, this module moves on to the three statements that change data rather than only reading it, INSERT, UPDATE, and DELETE, each of which uses a WHERE clause exactly like the ones built in this lesson to decide which rows to change. The comparison, range, set, pattern, and NULL-handling techniques covered here carry forward unchanged into every one of those statements.

SEMrush Software 3 SEMrush Banner 3