Explanation: EXCEPT query returns records in the blue area, only in data set 1 and not in data set 2.
Each SELECT statement in the EXCEPT query must have the same number of fields in the result set with the same data type.
SELECT bieu_thuc1thuc1, bieu_thuc2, … bieu_thucn
FROM bang
[WHERE dieu_kien]
EXCEPT
SELECT bieu_thuc1, bieu_thuc2, … bieu_thucn
FROM bang
[WHERE dieu_kie
n];
bieu_thuc
The column or value you want to compare between the SELECT statements. They do not need to be in the same information field at each SELECT statement but the corresponding columns must have the same data.
state
Table wants to get records from there. Must have at least 1 table in the FROM clause.
WHERE dieu_kien
Option. Conditions must satisfy for the selected record.
Note:
For example - with 1 expression
SELECTsanpham_id
FROM sanpham
EXCEPT
SELECT sanpham_id
FROM hang
tonkho;
In the example with this EXCEPT operator, the result returns all the sanpham_id values in the table of variables and not in the hangtonkho table. This means that if the sanpham_id value is available on both tables, it will not be returned.
For example - with multiple expressions
SELECT danhba_id, ho, ten
FROM danhba
WHERE ho = 'Anderson'
EXCEPT
SELECT nhanvien_id, ho, ten
FROM nhanvien
;
In this example, the query returns the records in the namba table with the contact ID, the first and last names do not match the employee's ID, last name, and first name in the table.
For example - use the ORDER BY clause
SELECT nhacung_id, nhacung_ten
FROM nhacung
WHERE bang = 'Florida'
EXCEPT
SELECT congty_id, congty_ten
FROM congty
WHERE congty_id <= 400
ORDER BY 2;
In this example, because the column name in the two SELECT statements is different, it is easier to refer to the column by the ORDER BY clause through the position in the result set. In the above example, we filter the result nhacung_ten / congty_ten in ascending order through the phrase ORDER BY 2.
Because the nhacung_ten / congty_ten is the 2nd in the result set.
Previous article: INTERSECT operator in SQL Server
The following article: Query SUBQUERY child in SQL Server