Search code examples
c#databasepostgresqlnpgsql

Copy a csv column into postgresql with autoincrement


I have a csv file with 1.2 million entrys which are representing analog values e.g. current values. When I save a data record I want to insert this values in one go.

When my software has the next run, it needs to know what was the last primary key id. I thought it would be possible that the primary key stuff is handled implicite so that the next run get's it's correct primary key automatically.

In my PostgreSQL database I have the following table

CREATE TABLE tbl_test
( id INTEGER primary key,
  value INTEGER
);

Additionally I have a csv coded file with only one column. The Content is as the following:

 value 
------
  89     
  12    
  234  

Then I used the following command to insert my values.

Using writer = conn.BeginTextImport("COPY tbl_test (value) FROM
'C://temp//analog.csv'")

I expected, that the result would be like in the following table, but It wasn't possible to insert the datas like I exptected.

Is it possible to add the content of the csv file with help of the COPY command so that the id column is incremented automatically and the result would be as the following?

 id  | value 
-----+-------
   1 |  89
   2 |  12
   3 |  234

Solution

  • not sure what was wrong in comments and why did not you try serial:

    t=# CREATE TABLE tbl_test
    ( id serial primary key,
      value INTEGER
    );
    CREATE TABLE
    
    t=# copy tbl_test (value) from stdin;
    Enter data to be copied followed by a newline.
    End with a backslash and a period on a line by itself.
      89
      12
      234  >> >> >>
    >> \.
    COPY 3
    t=# select * from tbl_test;
     id | value
    ----+-------
      1 |    89
      2 |    12
      3 |   234
    (3 rows)