---
title: "[SQL使用经验]选用 IN 还是 EXISTS，哪个性能更好"
author: "piedpiper"
date: "2006-09-12T10:08:00Z"
tags: ["SQL"]
slug: "sql-in-exists"
draft: false
lastmod: "2006-09-12T10:08:00Z"
id: 232285
url: "https://piedpiper.iteye.com/blog/232285"
---

一、EXISTS 并非总比IN 快，究竟应该选用 IN 还是 EXISTS ，可参考以下分析：  
1、Select * from t1 where x in ( select y from t2 )  
相当于  
select *  
  from t1, ( select distinct y from t2 ) t2  
 where t1.x = t2.y;

2、select * from t1 where exists ( select null from t2 where y = x )  
相当于  
   for x in ( select * from t1 )  
   loop  
      if ( exists ( select null from t2 where y = x.x )  
      then  
         OUTPUT THE RECORD  
      end if  
   end loop

如果t2的记录很多而t1的记录相对较少的话，建议采用第二种写法；相反，如果t1的记录很多而t2的记录相对较少，则建议采用第一种写法。  
其它情况，则需要仔细分析再决定是选择IN还是选择EXISTS

二、NOT IN 并不等价于NOT EXISTS

例如下面这两个句子，只有在t1.c1不为NULL的时候，两者返回的记录才是相同的，大家在用NOT EXISTS来替换NOT IN 时可能会忽略掉这一点  
select t1.*  
  from table1 t1  
 where not exists  
 (select t2.c1 from table2 t2 where t2.c1 = t1.c1)

select t1.*  
  from table1 t1  
 where t1.c1 not in (select t2.c1 from table2 t2)