Avatar of Star79
Star79
Flag for United States of America asked on

SQL - NOT IN

Hello all,
I have the following tables:
Rxs has columns rxno,patid,rono,drug
Rxadmin has columns rxno,patid,rono,admintime.
How to write a query to find all the rono which are in Rxs table but not present in Rxadmin table.
I wrote the below sql
SELECT rono,patid
       
FROM   [rx].[dbo].[rxs] 
WHERE  rxs.rono NOT IN (SELECT rono
                             FROM   [rx].[dbo].[rxadmintimes]
                             WHERE  rono IS NOT NULL) 
                             order by rxs.RoNo

Open in new window

Somehow its not giving the right results
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
Shaun Kline

8/22/2022 - Mon
guswebb

select * from rxs where not rxno in (select rxno from rxadmin)
Shaun Kline

Your query is syntactically correct. Are you missing rows in your results or do you have extra rows?
guswebb

sorry, that should have been...

select * from rxs where not rono in (select rono from rxadmin)
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Star79

ASKER
my query is missing rows
I also tried
select * from rxs where not rono in (select rono from rxadmin)
still missing rows
ASKER CERTIFIED SOLUTION
Jim Horn

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Shaun Kline

Try this:
SELECT rono,patid
FROM   [rx].[dbo].[rxs] rxs
WHERE  NOT EXISTS (SELECT 1
                             FROM   [rx].[dbo].[rxadmintimes]
                             WHERE  rxs.rono = rono
                             AND rxs.rxno = rxno) 
ORDER BY rxs.RoNo

Open in new window


This SQL assumes that RXNo is a linking field between the two tables along with rono.

The NOT EXISTS is considered more efficient that using a NOT IN query.