[Switch] The difference in sql and not in, exists not exists with the

1、in和exists

in that the outer and inner tables for the hash join, and exists as a loop cycle is the appearance of each loop recycled inner table query, it has been considered to be inaccurate than exists in high efficiency argument. If the query two tables of comparable size, and exists in it with little difference; if two tables in a small a large, large look-up table of the child with exists,

A small table with a subquery in;

For example: Table A (small table), Table B (large table)

SELECT  *  from A WHERE cc in ( SELECT cc from B)  - > inefficiency, the index used in Table A cc column; 
SELECT  *  from A WHERE  EXISTS ( SELECT cc from B WHERE cc = a.cc)  - > high efficiency, the use of the index table B cc column.

The opposite of:

SELECT  *  from B WHERE cc in ( SELECT cc from A)  - > high efficiency, uses the index table cc column B 
SELECT  *  from B WHERE  EXISTS ( SELECT cc from A WHERE cc = B.cc)  - > Efficiency low, use the index on the table a cc column.

2、not in 和not exists

not in the logic is not exactly the same not exists, if you misuse not in, carefully fatally BUG your program, see the following example:

create table #t1(c1 int,c2 int);
create table #t2(c1 int,c2 int);
insert into #t1 values(1,2);
insert into #t1 values(1,3);
insert into #t2 values(1,2);
insert into #t2 values(1,null);
select *  From # T1 WHERE C2 Not  in ( SELECT C2 from # T2);  - > execution result: no 
SELECT  *  from # T1 WHERE  Not  EXISTS ( SELECT  . 1  from # T2 WHERE # t2.c2 = # T1.c2)  - > The results: 13

As can be seen, not in the emergence of undesired result set, there is a logical error. If you look at the execution plan of the two select statements, will be different, which uses a hash_aj, so please try not to use not in (it will call sub-queries), and try to use not exists (it will call correlated subqueries ). If any of the subquery returned record contains a null value, the query will not return any records. If there is non-empty sub-query field limit, then you can use not in, and can be connected with hasg_aj or merge_aj by prompting it.

If the query using not in, then the internal appearance are a full table scan, did not use the index; and the child still can not exists query to the index on the table. So no matter which table is large, not exists than not in fast.

3, in the difference =

select name from student where name in('zhang','wang','zhao');

versus

select name from student where name='zhang' or name='wang' or name='zhao'

The result is the same.

 

Guess you like

Origin www.cnblogs.com/AlbertLiu/p/11691517.html