简体   繁体   中英

pgAdmin/psql how to import new column's data to existing records?

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.

  1. Create temporary table in your db matching the CSV structure (I'm assuming the CSV contains 2 columns, a primary key and the new column data)
  2. Populate this temporary table with the CSV data using postgres' COPY command
  3. Run an UPDATE query to copy the data from the temporary table into your existing table
  4. DROP the temporary table and you're done!

sqlfiddle example

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM