Solved

sql 'not in' vs 'not exists'

Posted on 2014-04-01
3
262 Views
Last Modified: 2014-04-01
I am trying to convert a sql that has a sub query with 'not in' clause to a sql with 'not exist' for performance reasons, but i get different results in both my queries. Please help me understand and get the right query that would give me the same results as the 'not in'  query.

NOT IN sql :
		select 
			id, 
			'Patient',
			'Missing Name',
			null,
			'l_c_claim',
			'p_l_name',
			pat_last_name
		from wt_l_c_bill		
		where p_l_name IS NULL
			and id not in (select b_id from app_b_r_v_item where validation_category = 'Patient')

Open in new window


'NOT EXISTS'  sql
		select 
			id, 
			'Patient',
			'Missing Name',
			null,
			'l_c_claim',
			'p_l_name',
			pat_last_name
		from wt_l_c_bill b		
		where NOT EXISTS (Select 1 from app_b_r_v_item v where validation_category = 'Patient' and b.id = v.b_id)

Open in new window


Thank You
0
Comment
Question by:patd1
3 Comments
 
LVL 28

Accepted Solution

by:
sammySeltzer earned 250 total points
ID: 39969444
Have you considered adding this line to your NOT EXISTS query:

      
where p_l_name IS NULL

Open in new window


and besides, the two queries are different anyway.
0
 
LVL 142

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 250 total points
ID: 39969531
you shall add AND b_id IS NOT NULL into the NOT IN for NOT IN and NOT EXISTS to work the same.
but I also confirm that you have
where p_l_name IS NULL
in the first query, but not in the second.
0
 

Author Closing Comment

by:patd1
ID: 39969571
thanks got it.
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now