How to select distinct values on 2 columns in postgresql

Viewed 900

I have a table with col A and col B. Col A and Col B can have repetitive values. I want to select distinct values from Col A and Col B individually and populate them in 1 column as unique values. How do I do that?

Example

col_a | col_b
------+------
 1    | 3 
 2    | 4 
 3    | 5 
 4    | 7 
 5    | 8  
 6    | 

I want to extract the total unique values in a table that says 1,2,3,4,5,6,7,8. How do I do that?

2 Answers

You can use a UNION to combine two results with each column. A UNION will remove duplicates automatically:

select col_a as value
from the_table
union
select col_b 
from the_table;

One simple approach is to use a union:

SELECT DISTINCT val
FROM
(
    SELECT A AS val FROM yourTable
    UNION ALL
    SELECT B FROM yourTable
) t;

Demo

Related