The difference between in and exists in sql is the efficiency problem

in 和exists

in is a hash connection between the outer and inner table, and exists is a loop loop for the outer table, and the inner table is queried every time the loop is looped.

The long-standing belief that exists is more efficient than in is inaccurate. Using in and exists makes little difference if the two tables being queried are of the same size.

 

If one of the two tables is smaller and the other is a large table, use exists for the larger subquery table, and in for the smaller subquery table:

E.g:

Table A (small table), table B (large table) 1:

 

select*from A where cc in (select cc from B)

 

The efficiency is low, and the index of the cc column on the A table is used;

 

select*from A whereexists(select cc from B where cc=A.cc)

 

The efficiency is high, and the index of the cc column on the B table is used.

 

Opposite 2:

 

select*from B where cc in (select cc from A)

 

High efficiency, using the index of the cc column on the B table;

 

select*from B whereexists(select cc from A where cc=B.cc)

 

The efficiency is low, and the index of the cc column on the A table is used.

 

 

not in 和not exists

If the query statement uses not in, then both the inner and outer tables will perform a full table scan, and no index will be used;

The subquery of not extsts can still use the index on the table. So no matter the size of the table, using not exists is faster than not in.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326381618&siteId=291194637