David
David

Reputation: 229

Parenthesis in sqlite when combining UNION and EXCEPT statements

I need to run a query like A EXCEPT (B UNION C) in sqlite. The problem is that when I insert the parentheses in the statement I get a syntax error.

I have tried to run the following statement:

SELECT col1 FROM tab1 WHERE x=val1 EXCEPT (SELECT col2 FROM tab2 WHERE x=val1  UNION SELECT col3 FROM tab3 WHERE x=val1);

and I get Error: near "(": syntax error.

If I remove the parenthesis the statement executes but the EXCEPT is run before the UNION and that's not what I need. What is the proper way to run the query above as a single statement?

Upvotes: 2

Views: 968

Answers (1)

forpas
forpas

Reputation: 164139

This is the correct syntax:

SELECT col1 FROM tab1 WHERE x=val1 
EXCEPT 
SELECT * FROM (
  SELECT col2 FROM tab2 WHERE x=val1  
  UNION 
  SELECT col3 FROM tab3 WHERE x=val1
);

See the demo.

Upvotes: 1

Related Questions