I have several tables in a database of PostgresQL that contains users' records. I would like to add a new column to user's table and was wondering how I can import data of that new column.
I have a CSV file but can't work out the best way to import the data without overwriting any existing records.
Thanks in advance.
I don't think your request is possible with a single psql
command, but I think you can achieve what you're going for in a few steps.
COPY
commandUPDATE
query to copy the data from the temporary table into your existing tableDROP
the temporary table and you're done! DDL
-- existing table in your db
create table my_table (
id integer PRIMARY KEY,
some_col integer
);
-- some dummy data
insert into my_table (id, some_col)
values (1, 111), (2, 222), (3, 333);
-- create temp_table with same structure as CSV
create table temp_table (
id integer PRIMARY KEY,
new_col_val text
);
-- some dummy data, but you can use postgresql's COPY command to copy data from a CSV
-- docs: https://www.postgresql.org/docs/current/static/sql-copy.html
insert into temp_table (id, new_col_val)
values (1, 'hello'), (2, 'hi'), (3, 'hey');
Queries
-- view initial contents of my_table
select * from my_table;
-- view initial contents of temp_table
select * from temp_table;
-- add new column to my_table
alter table my_table add column new_col text;
-- populate new column with data from temp_table
update my_table set new_col = new_col_val
from temp_table
where my_table.id = temp_table.id;
-- view results
select * from my_table;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.