SUBHAS PATIL
SUBHAS PATIL

Reputation: 152

Postgres query to combine two column values

Lets say I have a postgres table with the following data:

hostname | ip
---------+--------
a1       | 198.162.4.2
a1       | 198.162.7.5
a2       | 10.43.243.4
a3       | 10.3.1.1

I want to copy the values from table tmp to table abc in psql. I want to have an sql insert command to display the hostname_ip in hostname column like below:

hostname | ip
---------+--------
a1_198.162.4.2 | 198.162.4.2    
a1_198.162.7.5 | 198.162.7.5
a2_10.43.243.4 | 10.43.243.4
a3_10.3.1.1    | 10.3.1.1

Upvotes: 0

Views: 38

Answers (3)

Sridhar
Sridhar

Reputation: 11

SELECT CONCAT(hostname,'_',ip) as hostname,ip FROM table;

Upvotes: 0

trempo
trempo

Reputation: 58

You can do like below

insert into abc(hostname,ip)
select (hostname || '_' || ip) as hostname,ip from tmp;

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

I suggest using CONCAT_WS here:

SELECT CONCAT_WS('_', hostname, ip) AS hostname, ip
FROM yourTable;

Upvotes: 1

Related Questions