7

I have the following query:

select col1, col2
from ...
where...

which gives:

col1  col2
5
       17
4       5
12
5
       20
4      17
2       3

I want to convert it to one column with no duplicates as follows:

col3
5
17
4
12
20
2
3

How can I do that? I read this topic Combine two columns and add into one new column but it's not what I need... operator || won't help here.

Edit: col3 is simply a list of all numbers that appear in col2 and col1.

2
  • third row has 4, not 5 - why? is there a rule to use first column if both specified?.. try select coalesce(col1,col2) from table - it will use col1, and if col1 is null, then col2 Commented Aug 15, 2017 at 9:56
  • @VaoTsun The logic is show me all numbers that appear in any of the columns but with no duplicates. col3 is simply a list of all numbers that appear in col2 and col1. Commented Aug 15, 2017 at 10:02

4 Answers 4

8

It seems you need union

select col1 as col3 from t where col1 is not null
union
select col2 as col3 from t where col2 is not null
Sign up to request clarification or add additional context in comments.

Comments

5
select coalesce(col1,col2) 
from table 

it will use col1, and if col1 is null, then col2

https://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display

2 Comments

coalesce is not enough... I edited my example to show why. The number 3 will never appear in the final result using coalesce.
in your sample between 20.....2, 3 are missing 4, 17 - is it because you want distinct values only? I answered thinkng you want to combine two columns, not just select both columns as one
1

You can use the COALESCE function as documented at https://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL ; it returns the first of its arguments that is not null:

yesql# select col1, col2, coalesce(col1, col2) from foo;
 col1 │ col2 │ coalesce 
══════╪══════╪══════════
    5 │    ¤ │        5
    ¤ │   17 │       17
    4 │    5 │        4
   12 │    ¤ │       12
    5 │    ¤ │        5
    ¤ │   20 │       20
    4 │   17 │        4
(7 rows)

Comments

0

col3 is simply a list of all numbers that appear in col2 and col1.

In that case, this might be what you are looking for:

SELECT col1
FROM ...
WHERE ...
UNION
SELECT col2
FROM ...
WHERE ...

Comments

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.