Postgresql – COUNT with set DIFFERENCE and UNION

exceptpostgresql

Fairly simple question that I can't seem to find an answer to – I'm working with unions and differences, and I would like to perform a COUNT on the results. Currently I'm having to pipe out to a file and "wc -l" the file (minus 4 for the Postgres printing). There's got to be a way to include COUNT…

SELECT tbl1.id EXCEPT (SELECT tbl2.id UNION tbl3.id); 

I would like to know the number of results after the set difference. Thanks for any input!

Best Answer

Here you go:

SELECT COUNT(*) FROM (
    SELECT tbl1.id
    FROM tbl1 EXCEPT
    (
    SELECT tbl2.id
    FROM tbl2

    UNION

    SELECT tbl3.id
    FROM tbl3
    )
) AS t;