Leo Ribeiro
Leo Ribeiro

Reputation: 1255

Need to join 2 columns into only one using PostgreSQL

I need to join 2 columns into only one as follows.

enter image description here

Upvotes: 1

Views: 54

Answers (4)

Tim OMalley
Tim OMalley

Reputation: 423

Union works, I would also add "order by"

select a.follower_id "Connections" 
from table_name a 
union 
select b.followed_id
from table_name b
order by "Connections"

Upvotes: 0

Radim Bača
Radim Bača

Reputation: 10711

If the values are in one table then use cross join with lateral. It uses just one table scan.

SELECT v.*
FROM   table, LATERAL (
   VALUES
      (follower_id )
    , (followed_id)  -- data types must be compatible
   ) v ("connections")

similar question: Select distinct on multiple columns

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133400

You could use union

If both the columns are in the same table

select connection from my_table
union 
select followed_id from my_table

or change the table name if are in different tables

select connection from my_table1
union 
select followed_id from my_table2

Upvotes: 3

Ward
Ward

Reputation: 2828

select * from (
    select follower_id from T
    union
    select followed_id from T
)

Upvotes: 2

Related Questions