Re: NOT IN More Efficient???
From: Vishal Parkar (REMOVE_THIS_vgparkar_at_yahoo.co.in)
Date: 05/22/04
- Previous message: bob: "NOT IN More Efficient???"
- In reply to: bob: "NOT IN More Efficient???"
- Messages sorted by: [ date ] [ thread ]
Date: Sat, 22 May 2004 18:42:37 +0530
hi bob,
You can try the same query with not exists.
Internally in and exists clauses are evaluated differently.EXISTS clause
checks for the subquery returns at least one row. I would rely on exists as
compared to IN clause. You may see unexpected result set using not in clause
in following situation. From performance point of view i would give a go
ahead to NOT EXISTS compare to NOT IN, also make sure you have necessary
indexes on the columns that are part of join.
This is typical scenario when checking non-existing rows from the table.
use northwind
go
--create sample data table with one row that has customerid null.
select top 5 customerid into #t_exists from customers union all select null
select * from customers
where customerid not in(select customerid from #t_exists)
If any of the rows from the subquery returns null value and if you are using
NOT IN clause then you will get any empty resultset , as shown above.
You can use NOT EXISTS clause or LEFT OUTER JOIN to get the required result
set, NOT EXISTS would be faster compare to NOT IN. However you can see the
execution plan and resultant time to retrieve the result set. Also make sure
you have indexes on required columns to be joined.
1st method:
select * from customers
where not exists
(select * from #t_exists a
where a.customerid = customers.customerid)
2nd method:
select a.*
from customers a left outer join #t_exists b
on a.customerid = b.customerid
where b.customerid is null
-- Vishal Parkar vgparkar@yahoo.co.in | vgparkar@hotmail.com
- Previous message: bob: "NOT IN More Efficient???"
- In reply to: bob: "NOT IN More Efficient???"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|
|