create table items (
name varchar(15) not null,
id1 integer,
id2 integer,
UNIQUE(id1),
UNIQUE(id2)
);
insert into items (name, id1, id2) values
('a', 1, null),
('b', 2, null),
('c', null, 2);
select * from items where id1=2
union
select * from items where id2=2
and id2 not in (select id2 from items where id1=2);
I have a table where there are multiple fields containing the unique id belonging to a given item. In my example, either id1
or id2
contains this value. My goal would be to only rely on id2
if the item cannot be found via id1
. So, I would expect to always get back b
in my example.
I have managed to get this working via a union, but it seems like a very hacky solution with bad performance. A better solution seems to me is to filter on the client side. What do you think?
2
Answers
We can use
ROW_NUMBER
here:Each logical pair of records is described by
COALESCE(id1, id2)
being the same between them (if a pair exists). Within each pair, we choose the record having the lowestid1
value, which would mean the non null record.I would use
That relies on the fact that
FALSE < TRUE
.