Auto generate ID in massive PostgreSQL INSERT - sql

I try to copy a table into another, but the fields are not the same (it is not a problem), and some fields in table destination are optional.
I do somethink like this:
INSERT INTO data(Email, Title, FirstName, LastName)
SELECT champs5, champs1, champs3, champs4
FROM tmp
But the problem comes from the id field who is of course required:
ERROR: null value in column "id" violates not-null constraint
How can I tell to Postgres to auto generate the ID for each line of the INSERT?

Related

Id sequence is not incrementing after inserting a row with id

I have table user (id, firstname, lastname) and id is defined as
id int8 NOT NULL DEFAULT nextval('user_id_seq'::regclass)
But when I first insert a row through database using this SQL:
INSERT INTO user (id, firstname, lastname)
VALUES((SELECT(MAX(id) + 1) FROM user), firstname, lastname);
the data gets inserted, but when I am hitting through API then id is not returned, I get an error
duplicate key value violates unique constraint 'user_pkey'
This is because in the previous insertion through database sequence is not updated.
How to resolve this?
The only good way to prevent that is to use an identity column instead:
ALTER TABLE tab
ALTER id
ADD GENERATED ALWAYS AS IDENTITY (START 1000000);
That automatically creates a sequence, and a normal insert statement is not allowed to override the default.

Add primary key to an existing table

How to add a primary key to an existing table in SQLite? I know that I have to generate a new table and copy everything from the old table. However, it keeps giving me an error saying datatype mismatch due to one table having a primary key and the other one not. I did run the same commands without including primary key and it works.
CREATE TABLE temp_table
(
id INTEGER PRIMARY KEY,
age INTEGER,
address TEXT
)
INSERT INTO temp_table
SELECT *
FROM original_table
Since I am importing the data from a CSV file I do not know how to add the PRIMARY KEY in the first place. In case anyone knows a solution for that it would also work.
Assuming that the original table has 2 columns: age and address, you can either list the column names of the new table without the primary key:
INSERT INTO temp_table(age, address)
SELECT age, address FROM original_table
or, include the primary key and pass null for its value:
INSERT INTO temp_table(id, age, address)
SELECT null, age, address FROM original_table
or:
INSERT INTO temp_table
SELECT null, age, address FROM original_table
In all cases the id will be filled by SQLite, because it is defined as INTEGER PRIMARY KEY and it will be automatically autoincremented starting from 1.
If there is another column in the original table with unique integer values, you can pass that column to fill the new id:
INSERT INTO temp_table(id, age, address)
SELECT col, age, address FROM original_table
Change col to the actual name of the column.

Primary key not AUTO INCREMENT in the PostgreSQL

I have table Category and I have 3 columns category_id, category_name,category_description.
When I execute insert script without category_id parameter I have this error:
ERROR: null value in column "category_id" violates not-null constraint
DETAIL: Failing row contains (null, T_601, Yojimbo).
SQL state: 23502
This is my select script:
INSERT INTO category ( category_name, category_description)
VALUES ('T_601', 'Yojimbo');
This is the image of my table :
Change the data type to serial, which is Postgres's way of spelling auto_increment. If you have a not-NULL integer column with no default, then you will get an error when you attempt an insert.
If you assign a default, then the unique constraint (part of the primary key) will just create a duplicate key error on the second insert.
Use the following to add a serial to the column category_id
CREATE SEQUENCE cateogry_id_seq;
ALTER TABLE category ALTER COLUMN category_id SET DEFAULT nextval('cateogry_id_seq');
Now the column will be auto incremented and you don't have to enter the catgory_id column in insert queries

INSERTING a single field into a table, referenced from another table

I need to insert a field in a that references an id field in another table.
The id field it is to going is next to the field 'test' (column - codedescription, table typecategory) and coming from an id field next to the word 'assessment' (column categorydescription, table typecategory)
INSERT INTO codetype
(typecategoryid)
Where codedescription='test'
SELECT id FROM typecategory WHERE categorydescription='Assessment Types'
There are plenty of examples of inserting entire columns but nobody has written how to insert a single field from another table.
table - codetype
id bigserial primary key
codedescription varchar
typecategoryid bigint foreign key to typecatogory on the ID column
Table - typecategory
ID big serial primary key
categorydescription varchar
If the column already exists and there are are already records in the rest of the columns in the table, then you need an UPDATE statement, not an INSERT.
Looks like this post might help you: Update a column of a table with a column of another table in PostgreSQL
maybe
UPDATE codetype c
SET c.typecategoryid = t.id
FROM typecategory t
WHERE c.codedescription = 'test' and t.categorydescription='Assessment Types'

How to insert duplicate rows in SQLite with a unique ID?

This seems simple enough: I want to duplicate a row in a SQLite table:
INSERT INTO table SELECT * FROM table WHERE rowId=5;
If there were no explicit unique column declarations, the statement would work, but the table's first column is declared rowID INTEGER NOT NULL PRIMARY KEY. Is there any way to create a simple statement like the one above that works without knowing the schema of the table (aside from the first column)?
This can be done using * syntax without having to know the schema of the table (other than the name of the primary key). The trick is to create a temporary table using the "CREATE TABLE AS" syntax.
In this example I assume that there is an existing, populated, table called "src" with an INTEGER PRIMARY KEY called "id", as well as several other columns. To duplicate the rows of "src", use the following SQL in SQLite3:
CREATE TEMPORARY TABLE tmp AS SELECT * FROM src;
UPDATE tmp SET id = NULL;
INSERT INTO src SELECT * FROM tmp;
DROP TABLE tmp;
The above example duplicates all rows of the table "src". To only duplicate a desired row, simply add a WHERE clause to the first line. This example works because the table "tmp" has no primary key constraint, but "src" does. Inserting NULL primary keys into src causes them to be given auto-generated values.
From the sqlite documentation: http://www.sqlite.org/lang_createtable.html
A "CREATE TABLE ... AS SELECT" statement creates and populates a database table based on the results of a SELECT statement. A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind.
If you want to get really fancy, you can add a trigger that updates a third table which maps old primary keys to newly generated primary keys.
No. You need to know the schema of the table to write the insert statement properly.
You need to be able to write the statement in the form of:
insert into Table (column1, column2, column3)
select column1, column2, column3
from OtherTable
where rowId = 5
Well, since I was unable to do this the way I wanted, I resorted to using the implicit row id, which handily enough has the same name as the rowId column I defined explicitly, so now I can use the query I had in the question, and it will insert all the data with a new rowId. To keep the rest of the program working, I just changed SELECT * FROM table to SELECT rowId,* FROM table and everything's fine.
Absolutely no way to do this. Primary Key declaration implies this field is unique. You can't have a non unique PK. There is no way to create a row with existing PK in the same table.