Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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()
  
# 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',)

PostgreSQL Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :