AND conditions in SQL Server

In SQL Server, the AND condition (or AND operator) is used to test two or more conditions.

In SQL Server, the AND condition (or AND operator) is used to test two or more conditions in SELECT, INSERT, UPDATE, or DELETE statements.

AND condition syntax

 WHERE 'điều kiện 1' 
AND 'điều kiện 2'

AND 'điều kiện n';

Variable name or variable value

Condition 1, condition 2 . conditions n

The conditions that the record must meet to be selected.

Note

  1. The AND condition in SQL Server allows two or more conditions to be checked.
  2. The AND condition in SQL Server requires that all conditions be met and the new record is included in the result set.

For example - with SELECT statement

 SELE CT * 
FROM nhanvien
WHERE ho = 'Smith'
AND nhanvie n_id <499;

The result in this example will return all employees with the surname Smith and nhanvien_id less than 499. Because * is used in the SELECT statement, all fields in the table are in the result set.

Example - table combination

 SELECT nhanvien.nhanvien_id, danhba.ho 
FROM nhanvien, danhba
WHERE nhanvien.nhanvien_id = danhba.danhba_id
AND nhanvien.ten = 'Sarah';

Although the above example still works, it will usually need to be written in INNER JOIN.

 SELECT nha nvien.nhanvien_id, danhba.ho 
FROM nhanvien
INNER JOIN danhba
ON nhanvien.nhanvien_id = danhba.danhba_id
WHERE nhanvien. ten = 'Sarah';

In this example, the returned result will include all the rows with the employee's name as Sarah in the table. Table of names and names connected by nhienvien_id and danhba_id.

Note that all information fields are named after the table name (eg danhba.ten). This is required, to avoid ambiguity about the referenced information field, for example, when two tables have the same information field.

In this case, the returned result will only be displayed with the_id and cough.

Example - INSERT command

 INSERT INTO danhba 
(danhba_id, ho, ten)
SELECT nhanvien_id, ho, ten
FROM nhanvien
WHERE ten = 'Joanne'
AND nhanvien_id >= 800;

The AND condition in this example will insert the list of all fields, ten, and coughs from the table with those named Joanne and nhanvien_id greater than or equal to 800.

Example - UPDATE command

 UPDATE anvien 
SET ho = 'Johnson'
WHERE ho = 'TBD'
AND nhanvien _id <300;

This example will update all the values ​​in the table to Johnson when the employee's surname is valued as TBD and nhanvien_id less than 300.

Example - DELETE command

 DELETE FR OM nhanvien 
WHERE ten = 'Darlene'
AND ho = 'Hend erson';

This command will delete all records in the table if the employee is named Darlene and they are Henderson.

Previous article: ORDER BY clause in SQL Server

Next article: OR conditions in SQL Server

4.5 ★ | 2 Vote