redgate给出的提示

https://www.red-gate.com/hub/product-learning/sql-prompt/consider-using-not-exists-instead-not-subquery

Phil Factor explains why you should prefer use of [NOT] EXISTS over [NOT] IN, when comparing data sets using a subquery.

While there is no longer any significant performance advantage, using NOT EXISTS will avoid unexpected results when the subquery’s source data contains NULL values.

It used to be that the EXISTS logical operator was faster than IN, when comparing data sets using a subquery. For example, in cases where the query had to perform a certain task, but only if the subquery returned any rows, then when evaluating WHERE [NOT] EXISTS (subquery), the database engine could quit searching as soon as it had found just one row, whereas WHERE [NOT] IN (subquery) would always collect all the results from the sub-query, before further processing.

However, the query optimizer now treats EXISTS and IN the same way, whenever it can, so you’re unlikely to see any significant performance differences. Nevertheless, you need to be cautious when using the NOT IN operator if the subquery’s source data contains NULL values. If so, you should consider using a NOT EXISTS operator instead of NOT IN, or recast the statement as a left outer join.

A recommendation to prefer use of [NOT] EXISTS over [NOT] IN is included as a code analysis rule in SQL Prompt

https://documentation.red-gate.com/codeanalysis/performance-rules/pe019

In theory, EXISTS is faster because the search stops as soon as the condition is true, whereas IN has to collect all sub-query results before testing the condition.

In practice, the query optimizer treats EXISTS and IN the same way whenever it can.

Stack Overflow上的解释

https://stackoverflow.com/questions/24929/difference-between-exists-and-in-in-sql

I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: When would it be a good idea to rewrite the SQL to use IN instead of EXISTS, or vice versa.

Is that a fair assumption?


Edit: The reason I'm asking is that in many cases you can rewrite an SQL based on IN to use an EXISTS instead, and vice versa, and for some database engines, the query optimizer will treat the two differently.

For instance:

SELECT *
FROM Customers
WHERE EXISTS (
SELECT *
FROM Orders
WHERE Orders.CustomerID = Customers.ID
)

can be rewritten to:

SELECT *
FROM Customers
WHERE ID IN (
SELECT CustomerID
FROM Orders
)

or with a join:

SELECT Customers.*
FROM Customers
INNER JOIN Orders ON Customers.ID = Orders.CustomerID

So my question still stands, is the original poster wondering about what IN and EXISTS does, and thus how to use it, or does he ask wether rewriting an SQL using IN to use EXISTS instead, or vice versa, will be a good idea?

SQL Server IN vs. EXISTS Performance

EXISTS will be faster because once the engine has found a hit, it will quit looking as the condition has proved true.

With IN, it will collect all the results from the sub-query before further processing.

  • This used to be true but in current versions (at least 2008) the optimizer is much smarter... it actually treats IN () just like an EXISTS (). – Aaron Bertrand Jan 14 '10 at 16:51
  • @Aaron - yes, typically the optimzer will internally produce a better plan. However, relying on internal shortcuts could be detrimental in more complex scenarios.

Example

使用In

SELECT *
FROM dbo.CMS_Transformation
WHERE TransformationClassID IN ( SELECT ClassID
FROM dbo.CMS_Class
WHERE ClassName LIKE '%lisa%' );

使用Exists

SELECT *
FROM dbo.CMS_Transformation
WHERE EXISTS ( SELECT *
FROM dbo.CMS_Class
WHERE ClassName LIKE '%lisa%'
AND ClassID = CMS_Transformation.TransformationClassID );

对比

执行结果,因为数据量较少,看起来似乎是一样的

扩展

Not Exists 和Not In是完全不同的东西

https://stackoverflow.com/questions/129077/not-in-clause-and-null-values

To state it simply, why does query A return a result but B doesn't?

A: select 'true' where 3 in (1, 2, 3, null)

B: select 'true' where 3 not in (1, 2, null)

This was on SQL Server 2005. I also found that calling set ansi_nulls off causes B to return a result.

Query A is the same as:

select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null

Since 3 = 3 is true, you get a result.

Query B is the same as:

select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null

When ansi_nulls is on, 3 <> null is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.

When ansi_nulls is off, 3 <> null is true, so the predicate evaluates to true, and you get a row.

Consider using EXISTS instead of IN的更多相关文章

  1. SQL Server-聚焦IN VS EXISTS VS JOIN性能分析(十九)

    前言 本节我们开始讲讲这一系列性能比较的终极篇IN VS EXISTS VS JOIN的性能分析,前面系列有人一直在说场景不够,这里我们结合查询索引列.非索引列.查询小表.查询大表来综合分析,简短的内 ...

  2. SQL Server-聚焦NOT IN VS NOT EXISTS VS LEFT JOIN...IS NULL性能分析(十八)

    前言 本节我们来综合比较NOT IN VS NOT EXISTS VS LEFT JOIN...IS NULL的性能,简短的内容,深入的理解,Always to review the basics. ...

  3. 如何区别exists与not exists?

    1.exists:sql返回结果集为真:not exists:sql不返回结果集为真.详解过程如图: exists not exists

  4. LINQ to SQL语句(7)之Exists/In/Any/All/Contains

    适用场景:用于判断集合中元素,进一步缩小范围. Any 说明:用于判断集合中是否有元素满足某一条件:不延迟.(若条件为空,则集合只要不为空就返回True,否则为False).有2种形式,分别为简单形式 ...

  5. NOT IN 和NOT EXISTS

    今天写了一个简单的NOT IN语句,结果跟预期大相径庭,百度之发现深坑一个,遂录之. 登陆账户表logins code name status a admin N b guest N c member ...

  6. windows 部署 git 服务器报 Please make sure you have the correct access rights and the repository exists.错误

    这两天在阿里云上弄windows 服务器,顺便部署了一个git服务.根据网上教程一步步操作下来,最后在 remote远程仓库的时候提示 fatal: 'yourpath/test.git' does ...

  7. MySql中in和exists效率

    mysql中的in语句是把外表和内表作hash 连接,而exists语句是对外表作loop循环,每次loop循环再对内表进行查询.一直大家都认为exists比in语句的效率要高,这种说法其实是不准确的 ...

  8. SQL Server-聚焦LEFT JOIN...IS NULL AND NOT EXISTS性能分析(十七)

    前言 本节我们来分析LEFT JOIN和NOT EXISTS,简短的内容,深入的理解,Always to review the basics. LEFT JOIN...IS NULL和NOT EXIS ...

  9. SQL Server-聚焦EXISTS AND IN性能分析(十六)

    前言 前面我们学习了NOT EXISTS和NOT IN的比较,当然少不了EXISTS和IN的比较,所以本节我们来学习EXISTS和IN的比较,简短的内容,深入的理解,Always to review ...

  10. SQL Server-聚焦NOT EXISTS AND NOT IN性能分析(十五)

    前言 上一节我们分析了INNER JOIN和IN,对于不同场景其性能是不一样的,本节我们接着分析NOT EXISTS和NOT IN,简短的内容,深入的理解,Always to review the b ...

随机推荐

  1. [JSOI2012]玄武密码 题解(AC自动机)

    显然是AC自动机对吧 插入单词之后把文章在自动机上跑一遍,到达过的节点打上花火标记 之后检查一下每个单词有几个标记即可 可以把题目中的4个字母映射成abcd方便遍历 一定要记得把文章也映射啊! #in ...

  2. 【6.24校内test】T1 江城唱晚

    [题目背景] 墙角那株海棠,是你种下的思念. 生死不能忘,高烛照容颜. 一曲江城唱晚,重忆当年坐灯前, 青衫中绣着你留下的线. ——银临<江城唱晚> [问题描述] 扶苏是个喜欢一边听古风歌 ...

  3. Extjs杂记录

    1,页面跳转到另外一个页面 这段话的意思:取得恢复密码窗口,关闭这个窗口,页面跳转到Login页面 2,keypecial 当与导航相关的键(如箭头.tab键.Enter键.ESC键等)按下时,该事件 ...

  4. javaHashcode与equals

    转载自:http://blog.csdn.net/jiangwei0910410003/article/details/22739953 Java中的equals方法和hashCode方法是Objec ...

  5. UVA-1572 Self-Assembly(拓扑排序判断有向环)

    题目: 给出几种正方形,每种正方形有无穷多个.在连接的时候正方形可以旋转.翻转. 正方形的每条边上都有一个大写英文字母加‘+’或‘-’.00,当字母相同符号不同时,这两条边可以相连接,00不能和任何边 ...

  6. Intellij idea 生成for循环代码块

    itar 生成array for代码块 for (int i = 0; i < array.length; i++) { = array[i]; } itco 生成Collection迭代 fo ...

  7. 运行/调试你的PHP代码

    前言 没有任何一名程序员可以一气呵成.完美无缺的在不用调试的情况下完成一个功能或模块.调试实际分很多种情况.本篇文章我分享下自己在实际开发工作中的经验,我个人理解,调试分三种,注意我所讲的是调试并非测 ...

  8. JMeter测试websocket

    今天公司要测websocket,搞了一天踩了不少坑,关键是还没爬出来,BOSS让回家再理理思路,没办法到家就开干. 一.家里玩的还是2.1的,为了少踩坑,先下个JMeter5.1.1(他们说4版本也行 ...

  9. fillder抓取APP数据之小程序

    1.下载fillder ,fillder官网:https://www.telerik.com/fiddler 2.安装好后设置fillder: 工具—>选项,打开设置面板.选择HTTPS选项卡. ...

  10. 负载均衡之nginx+consul(自动更新路由)

    前几篇先是记载了如何通过nginx配置服务负载均衡,后面记载了如何通过 ocelot 配置 服务负载均衡,分别介绍了用webapi注册服务以及配置文件注册服务,通过ocelot webapi + co ...