Python Psycopg2 – Concatenate columns to new column
Last Updated :
17 Oct, 2021
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 ‘geeks’ 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 = "geeks" , user = 'postgres' ,
password = 'root' , host = 'localhost' , port = '5432'
)
conn.autocommit = True
cursor = conn.cursor()
sql =
cursor.execute(sql)
sql1 =
cursor.execute(sql1)
sql2 =
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',)
PostgreSQL Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...