The moose likes JDBC and Relational Databases and the fly likes How to use DB2 Except in this context? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "How to use DB2 Except in this context?" Watch "How to use DB2 Except in this context?" New topic

How to use DB2 Except in this context?

Thomas Kennedy
Ranch Hand

Joined: Jan 20, 2008
Posts: 137
I'm doing a union between two DB2 resultsets I'll call yellow and pink.

key, source
select distinct
key, "yellow" as source
from x

union all

select distinct
key, "pink" as source
from y


The requirement is to omit from pink all those rows where key is in the yellow resultset. (Actually the union is between three resultsets but I have omitted the middle one.) How do I fit the EXCEPT in here?
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3733

What do you need to help with: the syntax, or the set operations? (Or both?)

Perhaps I'm not experienced enough, but this seems like a requirement that doesn't easily fit into SQL constructs. You could use EXCEPT, but you'd have to do this before adding the SOURCE column, because that would cause the otherwise identical "yellow" and "pink" records to differ. So you'd have to process "yellow" records twice (once with the EXCEPT clause, and once with the UNION clause).

Another approach could be to create a union including the SOURCE column, and then use a GROUP BY to keep only one version of each row. SOURCE would not be part of the group by, but you'd use MAX(SOURCE) which would choose "yellow" in rows that have both "pink" and "yellow" versions. Handling three colors this way could be tricky, but you could always use numbers to make the handling easier and translate it to a string later.

It would be probably good to try several approaches and see which one has the best execution plan.
I agree. Here's the link:
subject: How to use DB2 Except in this context?
It's not a secret anymore!