5

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?

1
  • Should the result include or exclude the null value? (The col_b value from the row where col_a = 6.) Commented Sep 18, 2018 at 6:58

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

If you would use UNION instead of UNION ALL you wouldn't need the DISTINCT.
@S-Man You're right, but someone else already beat me to this better answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.