2

I want to store a table into postgres 8.4 (edited previously stated:8.1) using pandas.DataFrame.to_sql via sqlalchemy using the following command.

df.to_sql("table_name",engine)

I am using postgres. How can I get set a PRIMARY KEY in this table that I am adding to the database? I tried to use the option index in the df.to_sql however, that does not seem to work.

3
  • 1
    Postgres 8.1 is more than 10 years old and is not supported. Please consider updating to a supported postgres version. Commented Mar 23, 2016 at 15:44
  • I don't have a DF-specific answer, but you can always add the primary key after the fact. Commented Mar 23, 2016 at 16:08
  • Hi, I am using 8.4.20. sorry about that. If it is not DF specific, how can it be changed after the fact...that may be just as good. Thanks in advance Commented Mar 23, 2016 at 20:00

1 Answer 1

2

If your df contains a column "id" which you want to use as PRIMARY KEY, then do this:

df.to_sql('table_name', engine, if_exists="append", index=False)
with engine.connect() as con:
    con.execute('ALTER TABLE table_name ADD PRIMARY KEY (id);')
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will also work if you have created say a serial primary key in the table beforehand. index=False will allow you to insert the other cols. The primary key will auto-increment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.