How can I Insert and update in one query - sql

Trying to write insert and update in the query. So my scenario is - If a row exists then do upsert and insert a new row. But row didn't exist only do insert.
So here what I am trying -
Select exist(Select 1 from table where condition)
if(exists){
Update table set column =value where condition.
Insert into table (column) values (" ").
}else{
Insert into table (column) values (" ")
}
As I am writing here so many queries, is there any possibility I can cover all these in one query.
Thanks in advance

You can write just insert query and check for CONFLICT CLAUSE.
Postgresql supports conflict clause, which is triggered when there was some conflict regarding particular CONSTRAINT.
Lets say you have table t with primary key column id and name field:
CREATE TABLE t ( id integer primary key, name varchar(255));
You can check primary key constraint, when you insert:
INSERT INTO t (id, name) VALUES (1, 'Name1')
ON CONFLICT ON t_id_constraint
DO UPDATE SET name='Name1';
t_id_constraint is constraint name for id column uniqueness.
This query will insert new values to table when there is no conflict and will update when new id is found on table.
Original answer

Related

Avoid inserting duplicates when using autoincrementing index

I have a query:
INSERT INTO tweet_hashtags(hashtag_id, tweet_id)
VALUES(1, 1)
ON CONFLICT DO NOTHING
RETURNING id
which work fine and inserts with id = 1, but when there is a duplicate let's say another (1, 1) it inserts with an id = 2. I want to prevent this from happening and I read that I can do ON CONFLICT (col_name) but that doesn't really help because I need to check for two values at a time.
The on conflict clause requires a unique constraint or index on the set of columns that you want to be unique - and it looks like you don't have that in place.
You can set it when you create table table:
create table tweet_hashtags(
id serial primary key,
hashtag_id int,
tweet_id int,
unique (hashtag_id, tweet_id)
);
Or, if the table already exists, you can create a unique index (but you need to get rid of the duplicates first):
create unique index idx_tweet_hashtags on tweet_hashtags(hashtag_id, tweet_id);
Then your query should just work:
insert into tweet_hashtags(hashtag_id, tweet_id)
values(1, 1)
on conflict (hashtag_id, tweet_id) do nothing
returning id
Specifying the conflict target makes the intent clearer and should be generally preferred (although it is not mandatory with do nothing).
Note that the query returns nothing when the insert is skipped (that is, the existing id is not returned).
Here is a demo on DB Fiddle that demonstrates the behavior with and without the unique index.

SQL server inserting values from one table to another

I am trying to insert a column of data from one table to another. The table I am trying to insert into is called MU.PROVIDERS. The table I am inserting from is called Sheet1$. (Imported from an excel sheet). The columns they have in common is called "NPI", a key that is common for all providers, so I am trying to insert based on this key. Not every NPI value in the Sheet1$ will put a corresponding RELAY_ID value into the 'MU.PROVIDERS' table. (There are more NPI's in the 'MU.PROVIDERS' than in Sheet1$) My query is as follows:
INSERT INTO [MU.PROVIDERS] (RELAY_ID)
SELECT h.RELAY_ID
FROM Sheet1$ as h JOIN
[MU.PROVIDERS] as i ON h.NPI = i.NPI;
I am getting the error:
Cannot insert the value NULL into column 'NPI', table 'MU.PROVIDERS'; column does not allow nulls. INSERT fails.
I do have the NPI column set as the primary key on the 'MU.PROVIDERS' table, but I am not inserting anything into this column so I do not understand the problem.
I think you want an update. Insert adds new rows. Update changes the values of columns:
UPDATE i
SET relay_id = h.relay_id
FROM mu.Providers i JOIN
Sheet1$ h
ON h.NPI = i.NPI;
You may have defined the NPI column as the primary key.
But the primary key needs a unique value to identify a row.
If you don't provide the value with your INSERT statement you should define the NPI column as IDENTITY(1,1) to automagically create a new identity value.

inserting unique primary key exception

I was trying to insert records to a table using statement like
insert into table
(table_id, xxx,xxx)
values
(100,xxx,xxx)
and get the unique violation on the primary key.
and i did a select
select * from table where table_id = 100;
There is no record there.Thought insert before then, delete record.
And if i dont insert the table id, i got a null violation.
I was wondering if there is anyway to deal with this(maybe sequence)? I need to insert several thousands records using the inserting statement. some hundered have this prob.
Thanks in Advance!

How can I insert into a table that is connected to another table with a 1-1 relationship

I dont know much about SQL, and I've got a problem using it.
I have two tables that connected to each other 1-1
Tbl1 (int_id1, str_desc1,....) and
Tbl2 (int_id2, str_desc2,....)
And these two are connected to each other
int_id1 ---- int_id2
First I want to know that is my design true?
And how can I insert into one of these of two together.
Cause I've got problem when I try to insert into one
here's the error description:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Tbl2_Tbl1". The conflict occurred in database "project", table
"dbo.Tbl1", column 'int_id1'.
Tnx...
It means you are trying to insert a value in a Foreign Key Column which does not exist in the Primary Key Column which it referencing to.
Any value you add in a Foreign Key Column, It must Exist in the Primary Key Column to which it referencing to, after all that is the whole Idea of adding Foreign Key Constraints. so you will not end up having orphan records in a table and also it reduces data redundancy.
Read Here for more information about Foreign Key Constraints.
First I want to know that is my design true?
When you have tables in a one to one relationship, the first question should be: why not just use one table? There may not be a need to separate the data.
Assuming you have 2 tables that have a 1to1 relationship. You can use a transaction to add rows to each. Lets say you have a Classes and Professors table, with a 1to1 relationship. Then you would do something like this:
begin tran;
insert into Classes (title) values ('Math 101');
insert into Professors(name) values ('Tim Rogers');
commit tran;
begin tran;
insert into Classes (title) values ('History 101');
insert into Professors(name) values ('Suzanne Bethany');
insert into Classes (title) values ('PE 101');
insert into Professors(name) values ('Emily Williams');
commit tran;
select * from Classes;
select * from Professors;

How to insert a row into a table that has only a single autoincrement column?

My table has only a single column calld id. This column is an autoincrementing key (I am using it for sequencing). I want to do something like: insert into sequencer; but this gives me SQL errors because I guess I need to have a values portion. But there are no other columns in the table and I want the id column to be autoincremented. I'd also rather not hack this by just adding another dummy column. Thanks.
INSERT INTO table SET id = NULL;
or
INSERT INTO table VALUES (NULL);
When inserting NULL into an auto-increment column, mysql will generate a new number instead.