Parenthesis in sqlite when combining UNION and EXCEPT statements

Viewed 493

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?

1 Answers

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.

Related