A trap that SQL often appears in the case of a not-in subquery with null values

Source: Internet
Author: User
Tags arithmetic

If the following: Table_a table and Table_b table, ask to query for records that are not in the Table_b table in the Table_a table.

 create TABLE [dbo].[ Table_a] ([ID] [nchar] ( 10  ) NULL, [Name] [ NCHAR] ( 10  001   Zhang San  002   John Doe  003   Harry CREATE TABLE [dbo]. [Table_b] ([ID] [nchar] ( 10   10   002   John Doe NULL Harry  
View Code

It is very easy for us to do the first time:

SELECT  *  from     as a WHERE    not inch SELECT     b.id                      from as       b)

However, the query did not reach the expected

ID Name
001 sheets of three
003 Harry

The reason is simple: because null cannot do how to "manipulate"

– If NULL participates in arithmetic operations, the value of the arithmetic expression is null. (Example: +,-,*,/subtraction)

– If NULL participates in the comparison operation, the result can be treated as false. (e.g.:>=,<=,<> greater than, less than, not equal to)

– If NULL participates in the aggregation operation, the aggregation function is set to NULL. Except for COUNT (*).

--if there is a null value in the not in subquery, the data is not returned. (For the simplest explanation, please refer to the comments below)

--correct wordingSELECT  * fromDbo. Table_a asaWHEREa.ID not inch(SELECTb.id fromDbo. Table_b asbWHEREb.ID is  not NULL)--exclude null values to participate in operator comparisons                      --suggested modifications to the associated query method--correct wording 1SELECT  * fromDbo. Table_a asaWHERE    not EXISTS(SELECT *                      fromDbo. Table_b asbWHEREa.ID=b.id)--correct wording 2SELECT  * fromDbo. Table_a asa Left OUTER JOINDbo. Table_b asB ona.ID=b.idWHEREb.ID is NULL
View Code

A trap that SQL often appears in the case of a not-in subquery with null values

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.