In this post explains how to use the AND condition in SQL Server (Transact-SQL) with syntax and examples.
The SQL Server (Transact-SQL) AND condition (also called the AND Operator) is used to test for two or more conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
The syntax for the AND condition in SQL Server (Transact-SQL) is:
All of the conditions that must be met for the records to be selected.
The first SQL Server AND condition query involves a SELECT statement with 2 conditions.
For example:
This SQL Server AND example would return all employees who have a last_name of 'Smith' and have an employee_id less than 499. Because the * is used in the SELECT statement, all fields from the employees table would appear in the result set.
Our next SQL Server AND example shows how the AND condition can be used to join multiple tables in a SELECT statement.
For example:
Though the above SQL works just fine, you would more traditionally write this SQL as follows using a proper INNER JOIN.
For example:
This SQL Server AND condition example would return all rows where the first_name in the employees table is 'Julie'. And the employees and contacts tables are joined on the employee_id from the employees table and the contact_id from the contacts table. You will notice that all of the fields are prefixed with the table names (ie: contacts.last_name). This is required to eliminate any ambiguity as to which field is being referenced; as the same field name can exist in both the employees and the contacts tables.
In this case, the result set would only display the employee_id and last_name fields (as listed in the first part of the SELECT statement.).
This next SQL Server AND example demonstrates how the AND condition can be used in the INSERT statement.
For example:
This SQL Server AND condition example would insert into the contacts table, all employee_id, last_name, and first_name records from the employees table where the first_name is 'Joanne' and the employee_id is greater than or equal to 800.
This SQL Server AND condition example shows how the AND condition can be used in the UPDATE statement.
For example:
This SQL Server AND condition example would update all last_name values in the employees table to 'Johnson' where the last_name is 'TBD' and the employee_id is less than 300.
Finally, this last SQL Server AND example demonstrates how the AND condition can be used in the DELETE statement.
For example:
This SQL Server AND condition example would delete all records from the employees table whose first_name is 'Darlene' and last_name is 'Henderson'.