Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new column (Python list) to a Postgresql table?

I have a Python list newcol that I want to add to an existing Postgresql table. I have used the following code:

conn = psycopg2.connect(host='***', database='***', user='***', password='***')
cur = conn.cursor()
cur.execute('ALTER TABLE %s ADD COLUMN %s text' % ('mytable', 'newcol'))
conn.commit()

This added the list newcol to my table, however the new column has no values in it. In python, when I print the the list in python, it is a populated list.

Also, the number of rows in the table and in the list I want to add are the same. I'm a little confused.

Thanks in advance for the help.

like image 892
dtluther Avatar asked Apr 28 '26 16:04

dtluther


1 Answers

ALTER TABLE only changes table schema -- in your case it will create the new column and initialize it with empty (NULL) values.

To add list of values to this column you can do: UPDATE TABLE <table> SET ... in a loop.

like image 185
Anant Bhardwaj Avatar answered Apr 30 '26 06:04

Anant Bhardwaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!