At my work, we came across a bug in our SQLite query that was returning strange results. The query looked a little bit like this:
SELECT * FROM TableA
WHERE TableA.ID NOT IN
(
SELECT TableA.ID -- Table A
FROM TableB -- Table B
);
What this query seems to return is all the results in TableA which are not in TableB.
You can try this your self:
CREATE TABLE `TableA` (
`ID` INTEGER,
PRIMARY KEY(ID)
);
CREATE TABLE `TableB` (
`ID` INTEGER,
PRIMARY KEY(ID)
);
INSERT INTO TableA (ID)
values (1),(2),(3);
INSERT INTO TableB (ID)
values (1),(2);
In this case, the above query will just return 3 (as 3 is not in TableB).
What I would like to know is what is actually going on here. How is this query valid, and why is it returning the results in A, not in B?
Personally I would have expected this query to return no results. I tried the same setup and query in Microsoft SQL Server where calling the above query will return no results.
Thanks
EDIT:
As noted in the comments, the intended and correct query should have been SELECT ID FROM TableB
in the sub query, which is why the strange behaviour was found.
select TableB.ID from TableB
(or justselect ID...
). The phraseselect TableA.ID from TableB
can only conceivably work when inside an outer select (as yours is) but as to what it should produce (and therefore exclude from the outer select) is unknown to me. My first guess is it would/should return one random/not-easily-predictable ID from TableA for each row that is in TableB, but it seems to be running as justselect ID from TableB
. – TripeHound Mar 9 '16 at 13:33select id...
, which is how this somewhat strange behaviour was stumbled upon. I wasn't sure if there was some sort of implicit JOIN occurring. – David Paton Mar 9 '16 at 14:33