Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite query with intersect and except

Tags:

sqlite

here is a sqlite query that I have to perform but i want to perform except operation first and then intersection. By default, intersection is given more precedence over except. Is there a way I can accomplish this?

select a, b from table1 intersect select a,b from table2 except  select a, b from table3

I tried putting the queries in brackets, but it threw me an error "[ near "(": syntax error ]".

select a, b from table1 intersect (select a,b from table2 except  select a, b from table3)
like image 450
Shashank Avatar asked Jun 07 '13 07:06

Shashank


1 Answers

Compound queries do not support parentheses, but subqueries do:

SELECT a, b FROM table1
INTERSECT
SELECT * FROM (SELECT a, b FROM table2
               EXCEPT
               SELECT a, b FROM table3)

Please note that INTERSECT does not have higher precedence than EXCEPT, the actual rules are:

When three or more simple SELECTs are connected into a compound SELECT, they group from left to right.

Since INTERSECT is commutative, you could simply write this particular query as:

SELECT a, b FROM table2
EXCEPT
SELECT a, b FROM table3
INTERSECT
SELECT a, b FROM table1 
like image 139
CL. Avatar answered Nov 06 '22 18:11

CL.