In this article, we are going to see how to concatenate multiple columns of a table in a PostgreSQL database into one column. To concatenate two or more columns into one, PostgreSQL provides us with the concat() function.
Table for demonstration:
In the below code, first, a connection is formed to the PostgreSQL database ‘neveropen’ by using the connect() method. after connecting to the database SQL update command is executed using the execute() command, which helps us create a new column called ’empno_name’, after creating the column, we use the update command to populate the new column with the concatenated values after concatenating columns ’empno’ and ‘ename’ from the above table. The third SQL command ‘select employee from empno_name;’ is used to view the concatenated column.
Below is the implementation:
Python3
import psycopg2 conn = psycopg2.connect( database = "neveropen" , user = 'postgres' , password = 'root' , host = 'localhost' , port = '5432' ) conn.autocommit = True cursor = conn.cursor() # adding an extra column sql = '''alter table employee add column empno_name varchar(30);''' cursor.execute(sql) # updating the new tables with values sql1 = '''UPDATE employee SET empno_name = concat(empno, ename);''' cursor.execute(sql1) # printing out the concatenated column sql2 = '''select empno_name from employee;''' cursor.execute(sql2) results = cursor.fetchall() for i in results: print (i) conn.commit() conn.close() |
Output:
('1216755raj',) ('1216756sarah',) ('1216757rishi',) ('1216758radha',) ('1216759gowtam',) ('1216754rahul',) ('191351divit',) ('191352rhea',)