tags:

views:

101

answers:

3

I have this working SQL statement:

select oriseqs.newID from oriseqs WHERE oriseqs.singlets=1 AND 
oriseqs.newID not in (select newID from cleanreport WHERE trash!="")

My question is how to avoid doing one select inside another in this particular case. I mean to rewrite the select statement in a way that there is no nested select.

Here is the relevant schema if needed:

CREATE TABLE cleanreport(newID TEXT, perc TEXT, inicoord INTEGER, endcoord INTEGER, ilen INTEGER, trash TEXT, comments TEXT);
CREATE TABLE oriseqs(newID TEXT, oldID TEXT, rawseq TEXT, singlets BOOLEAN);
+1  A: 

There are multiple ways to approach almost any problem in SQL. In your particular problem, the first alternative that springs to mind is to use a left outer join and test for null in a joined column on the second table. However, the query that you have is perfectly reasonable. I see no reason to change it and doubt - at least upon first inspection - that you'll see better performance from an alternative.

Mark Brittingham
the good thing about leaving it with a nested query, imho as a QA engineer, is that its easier to reverse engineer the query later on.
djangofan
That is another good point. The purpose of the left outer join solution is not nearly as obvious.
Mark Brittingham
A: 
select o.newID 
from            oriseqs     o
left outer join cleanreport c on c.newID = o.newID
WHERE o.singlets=1 
AND c.newID is null;
Carl Manaster
+3  A: 
SELECT oriseqs.newID 
FROM oriseqs AS o
LEFT JOIN cleanreport AS cr ON o.newID = cr.newID
WHERE oriseqs.singlets=1 
AND trash != ""
AND cr.newID IS NULL

What are the PKs?

le dorfier
Sorry, but what is "PKs"?
BlogueroConnor
Primary Keys for the two tables. I usually like to check the Primary Key for nullity
le dorfier
You should move 'AND trash != ""' to the ON clause. This will change (lessen) which rows are succesfully joined, which will in turn change which are filtered by 'AND cr.newID IS NULL'
Philip Kelley
It does not work your query in SQLite :(Anyway, I will leave it as it (with the nested select), but wanted to try it just for curious.
BlogueroConnor
What does "it does not work" mean??
John Machin