T-SQL Tutorial

T-SQL WHERE operator


In SQL Server, the WHERE operator is used in a SELECT statement to filter data based on a specified condition or set of conditions. The WHERE operator allows you to retrieve only the rows that meet a specific criteria, rather than returning all the rows from a table.


Syntax

The syntax for the WHERE operator is as follows:

SELECT column1, column2, ...
FROM table_name
WHERE condition;

The condition can be a simple comparison using one of the comparison operators (=, <>, <, >, <=, >=), or it can be a more complex expression that combines multiple conditions using logical operators (AND, OR, NOT).


Example

For example, the following query retrieves all rows from the "Customers" table where the "City" column contains the value "London":

SELECT *
FROM Customers
WHERE City = 'London';

You can also use the WHERE operator to filter data based on a range of values. For example, the following query retrieves all rows from the "Orders" table where the "OrderDate" column is between two dates:

SELECT *
FROM Orders
WHERE OrderDate BETWEEN '2022-01-01' AND '2022-12-31';

In addition to filtering data in a SELECT statement, the WHERE operator can also be used in an UPDATE or DELETE statement to modify or delete only the rows that meet a specified condition.

It's important to note that the WHERE operator can have a significant impact on query performance, especially when working with large tables. To improve performance, you can use indexes on the columns being filtered, or use more specific conditions to narrow down the number of rows being returned.