Abinash Nanda
Abinash Nanda

Reputation: 51

How to select distinct values on 2 columns in postgresql

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?

Upvotes: 5

Views: 2147

Answers (2)

user330315
user330315

Reputation:

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;

Upvotes: 6

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522752

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

Upvotes: 2

Related Questions