Skip to content
Advertisement

See if value exists in any column of every row in PostgresQL

Imagining I have this table, I want to be able to find the brands that exist associated with every id. Note that this is not equivalent to finding if the value exists for every row, since a single id may exist several times. The result I would expect in this case would be Mercedes-Benz.

 id |    brand1     |    brand2     |    brand3
----+---------------+---------------+---------------
  1 | Mercedes-Benz |               | Fiat
  2 | Honda         |               | Mercedes-Benz
  3 | Audi          |               | Audi
  3 | Audi          |               | Mercedes-Benz
  4 | Mercedes-Benz |               | Mercedes-Benz
  5 | Mercedes-Benz | Mercedes-Benz |
  5 | Mercedes-Benz | Mercedes-Benz |
  6 | Mercedes-Benz |               | Mercedes-Benz
  7 | Mercedes-Benz | Mercedes-Benz |
  8 | Audi          |               | Audi
  8 | Audi          |               | Mercedes-Benz

I have tried using EXIST, but I haven’t been able to find an elegant “postgresql” way to iterate in the id columns.

Result:

  |    brand      |  
  +---------------+
  | Mercedes-Benz | 

Advertisement

Answer

Unpivot the data — I recommend using a lateral join — and then aggregate:

select v.brand
from t cross join lateral
     (values (t.brand1), (t.brand2), (t.brand3)) v(brand)
group by brand
having count(distinct t.id) = (select count(distinct t.id) from t);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement