postgresql insert into table from select code example
Example 1: postgresql insert select
insert into items_ver(item_id, item_group, name)
select * from items where item_id=2;
Example 2: postgre insert select
insert into TABLENAMEA (A,B,C,D)
select A,B,C,D from TABLENAMEB
Example 3: insert record into table postgresql
try:
connection = psycopg2.connect(**postgres_credentials())
cursor = connection.cursor()
order_types = [(1,'SELL'),(2,'BUY')]
placeholders = ','.join(['%s']*len(order_types))
sql = f"""
INSERT INTO collection.instruction(id, side)
VALUES {placeholders}
"""
insert_statement = cursor.mogrify(sql, order_types)
print(insert_statement.decode('utf-8'))
cursor.execute(insert_statement)
connection.commit()
print('DB entries committed.')
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if connection:
cursor.close()
connection.close()