Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is, in SQLite, `SELECT (SELECT 1 UNION SELECT 2 UNION SELECT 3) INTERSECT SELECT 3 UNION SELECT 4` equal 4 and not 3?

In SQLite, if I type:

SELECT (SELECT 1 UNION SELECT 2 UNION SELECT 3) INTERSECT SELECT 3 UNION SELECT 4

I get the result 4. How is that possible?

SELECT 1 UNION SELECT 2 SELECT 3 is (1, 2, 3), right? And SELECT 3 UNION SELECT 4 is (3, 4). So, the intersect should be 3, right? What am I getting wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: Saying that INTERSECT is evaluated first does not answer my question, as ((1,2,3) INTERSECT (3)) UNION (4) is (3,4), rather than 4.

>Solution :

If you write your statement like this:

SELECT (SELECT 1 UNION SELECT 2 UNION SELECT 3) 
INTERSECT 
SELECT 3 
UNION 
SELECT 4

you can see that you are combining 3 SELECT statements with the operators UNION and INTERSECT.
All 3 statements should return the same number of columns.
Your 1st statement:

SELECT (SELECT 1 UNION SELECT 2 UNION SELECT 3)

actually returns only 1 row with 1 column, try it, which is the 1st row and the result is 1.

So your code is equivalent to:

SELECT 1 
INTERSECT 
SELECT 3 
UNION 
SELECT 4

which returns nothing for INTERSECT and finally UNION returns 4.

If you meant to write:

SELECT * FROM (SELECT 1 UNION SELECT 2 UNION SELECT 3) 
INTERSECT 
SELECT 3 
UNION 
SELECT 4

then the result would be (3, 4).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading