Skip to content
Related Articles
Open in App
Not now

Related Articles

Python Psycopg2 – Concatenate columns to new column

Improve Article
Save Article
  • Last Updated : 17 Oct, 2021
Improve Article
Save Article

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:


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);'''
# updating the new tables  with values
sql1 = '''UPDATE employee SET  empno_name = concat(empno, ename);'''
# printing out the concatenated column
sql2 = '''select empno_name from employee;'''
results = cursor.fetchall()
for i in results:



PostgreSQL Output:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!