PostgreSQL- insert result of query into exisiting table, auto-increment id - sql

I have created an empty table with the following SQL statement. My understanding (based on this tutorial: https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-serial/) was that SERIAL PRIMARY KEY will automatically provide an auto-incremented id for every new row:
CREATE TABLE "shema".my_table
(
id SERIAL PRIMARY KEY,
transaction text NOT NULL,
service_privider text NOT NULL,
customer_id text NOT NULL,
value numeric NOT NULL
)
WITH (
OIDS = FALSE
);
ALTER TABLE "shema".my_table
OWNER to admin;
Now I am querying another tables and would like to save the result of that query into my_table. The result of the query outputs following schema:
transaction
service_provider
customer_id
value
meaning the schema of my_table minus id. when I try to execute:
INSERT into my table
Select {here is the query}
Then I am getting an error that column "id" is of type integer but expression is of type text. I interpret it that the sql query is looking for id column and cannot find it. How can I insert data into my_table without explicitly stating id number but have this id auto-generated for every row?

Always mention the columns you want to INSERT:
INSERT INTO schemaname.my_table("transaction", service_privider, customer_id, value)
SELECT ?, ?, ?, ?;
If you don't, your code will break now or somewhere in the future.
By the way, transaction is a reserved word, try to use a better column name.

Related

How to efficiently insert ENUM value into table?

Consider the following schema:
CREATE TABLE IF NOT EXISTS snippet_types (
id INTEGER NOT NULL PRIMARY KEY,
name TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS snippets (
id INTEGER NOT NULL PRIMARY KEY,
title TEXT,
content TEXT,
type INTEGER NOT NULL,
FOREIGN KEY(type) REFERENCES snippet_types(id)
);
This schema assumes a one-to-many relationship between tables and allows efficiently maintaining a set of ENUMs in the snippet_types table. Efficiency comes from the fact that we don't need to store the whole string describing snippet type in the snippets table, but this decision also leads us to some inconvenience: upon inserting we need to retrieve snippet id from snippet_types and this leads to one more select and check before inserting:
SELECT id FROM snippet_types WHERE name = "foo";
-- ...check that > 0 rows returned...
INSERT INTO snippets (title, content, type) values ("bar", "buz", id);
We could also combine this insert and select into one select like that:
INSERT INTO snippets (title, content, type)
SELECT ("bar", "buz", id) FROM snippet_types WHERE name = "foo"
However, if "foo" type is missing in snippet_types then 0 rows would have been inserted and no error returned and I don't see a possibility to get a number of rows sqlite actually inserted.
How can I insert ENUM-containing tuple in one query?

Copying two columns from a foreign table into another table

INSERT INTO Confirmed (TotalDeaths, Population)
SELECT TotalDeaths, Population
FROM Deaths
WHERE UID IS NOT NULL;
Copy the values for the columns named TotalD and Pop from the Deaths Table to the Confirmed Table (same names, both contains UID primary Key)
Failed to execute query. Error:
Cannot insert the value NULL into column 'UID', table 'dbo.Confirmed'; column does not allow nulls. INSERT fails. The statement has been terminated.
I keep running into a problem where I get compiler errors due to the primary key not allowing nulls. I'm not sure where the null keys are even coming from when it shouldn't be null to begin with.
Both tables have very similar columns, but in this case all that needs to be mentioned is that there are three columns in both tables that are crucial, which are: UID int NOT NULL, TotalDeaths int NOT NULL, Population int NOT NULL.
Seems to be UID is not null column. Use below query
INSERT INTO Confirmed (UID, TotalDeaths, Population)
SELECT UID, TotalDeaths, Population
FROM Deaths
WHERE UID IS NOT NULL;

Postgres: Problems using insert with select

I have a table defined like this:
CREATE TABLE wp_master (
gid integer NOT NULL DEFAULT nextval('wp_master_gid_seq'::regclass),
name character varying(80),
....
type integer DEFAULT 4,
CONSTRAINT p_key PRIMARY KEY (gid),
);
I want to insert data into the table from another table so I
insert into wp_master ( name, .... type) select "NAME", ...., 1 from ."Tiri2011";
but I get the error:
ERROR: duplicate key value violates unique constraint "p_key"
DETAIL: Key (gid)=(2) already exists.
Why is postgres trying to put anything into the gid field when I have explicitly not included it in the list of columns? I assumed that gid pick up its value from the sequence.
Russell
Is is trying to insert the next value of the wp_master_gid_seq sequence. Declaring an id column as serial (auto-increment) will create a sequence which has a stored value of the last inserted id which was auto-incremented. If at anytime you inserted a gid value manually, it bypassed the sequence and the autoincrement function may become broken, because the sequence value did not get updated accordingly.
The easiest way to fix it is to change the value of the sequence to the (max gid value of your table) + 1. Just execute this once and you should be ok
select setval('wp_master_gid_seq', coalesce((select max(id)+1 from wp_master), 1), false)

How can I execute an `INSERT INTO` on a table with a string primary key?

I have two tables that are initialized with something like this:
create table foo (
"id" varchar(254) not null primary key,
"first_name" varchar(254) not null);
create table my_user (
"id" serial not null primary key,
"role" varchar(254) not null,
"first_name" varchar(254) not null);
The reason why the id column of foo is a varchar(254) instead of a serial is because in normal operations I'm inserting in an id provided by Google OAuth2 instead of generating my own id values.
I now have a set of records in a third table I call temp with the first_name column. I'm trying to emulate this post, but I'm not sure how to do so for string primary keys.
select * from (insert into my_user(id, role)
('some id value I want to generate, like historical || incrementing number',
[a fixed number],
select first_name from temp) returning id);
As it says in the official Postgres documentation, I know I need to get the arguments following the insert statement into the format of a table that matches the declaration of my_user. I guess I'm just lost as to how to generate a column of the ids I want here, or even a column of one number repeating.
Thanks for reading
You could insert a UUID (it's like a GUID) in your ID... It's guaranteed to be unique.
Sadly it's a little complex to load the module: Generating a UUID in Postgres for Insert statement?
Ah... and what wildplasser said, +1! :-)

Calculated columns in mysql on INSERT statements

Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
Is it possible to have the count column calculated for me whenever I do an insert?
e.g. do something like:
INSERT INTO log (date='foo');
and have count calculated by mysql.
Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.
Triggers are the best tool for annotating data when a table is changed by insert, update or delete.
To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:
create trigger log_date before insert on log
for each row begin
set new.date = current_date()
end;
You definitly have to declare what to insert. This should be possible by using the INSERT ... SELECT statement.
INSERT INTO log (date, count)
SELECT DATE() as date, count(id) as count
from foo;
Which should insert a new row into the log table, containing todays date and the number of rows in the foo table. (Assuming the foo table has an id column.. Use the primary key or another indexed column)
Why don't you use information_schema.TABLES?