I need to create a query to insert some records, the record must be unique. If it exists I need the recorded ID else if it doesnt exist I want insert it and get the new ID. I wrote that query but it doesnt work.
SELECT id FROM tags WHERE slug = 'category_x'
WHERE NO EXISTS (INSERT INTO tags('name', 'slug') VALUES('Category X','category_x'));
It's called UPSERT (i.e. UPdate or inSERT).
INSERT INTO tags
('name', 'slug')
VALUES('Category X','category_x')
ON DUPLICATE KEY UPDATE
'slug' = 'category_x'
MySql Reference: 13.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax
Try something like...
IF (NOT EXISTS (SELECT id FROM tags WHERE slug = 'category_x'))
BEGIN
INSERT INTO tags('name', 'slug') VALUES('Category X','category_x');
END
ELSE
BEGIN
SELECT id FROM tags WHERE slug = 'category_x'
END
But you can leave the ELSE part and SELECT the id, this way the query will always return the id, irrespective of the insert...
MySQL has nice REPLACE. It is easy to use and remember it's syntax as same as INSERT.
in you case, just run following query.
REPLACE INTO tags('name', 'slug') VALUES('Category X','category_x')
It acts like INSERT when no unique constraint violation. If duplicated value found on PK or UNIQUE key, then other columns will be UPDATED with given values. It is done by DELETE duplicated record and INSERT new record.
Related
I am trying to solve the problem with insert new value into table. Primary key is ID not email... Before insert i need check other records for email value. If no one match inserted email, data is inserted. But i canot write correct code for that...
IF EXIST (SELECT email FROM users WHERE email = "email")
THEN
BEGIN
'We Have Records of this Customer'
END
ELSE
BEGIN
INSERT INTO users
VALUES (null,'email9','password9','forename9','lastname9')
END
END IF
Or:
IF SELECT COUNT(*) FROM users WHERE email = 'email' > 0
THEN
BEGIN
//email exist
END
ELSE
BEGIN
//inserting
END
END IF
This looks like a good use case for MySQL INSERT ... ON DUPLICATE KEY UPDATE syntax.
First of all, you want to create a UNIQUE constraint on column email. This is the proper way to represent your business rule:
ALTER TABLE users ADD CONSTRAINT users_unique_email UNIQUE (email);
Now, if the record that is about to be inserted would generate a duplicate on the primary key or on that UNIQUE constraint, then MySQL lets you turn the operation to an UPDATE instead.
In your case, since you want not to update anything in that case, you can simply re-assign the email column (which we know is the same here).
Consider:
INSERT INTO users
VALUES (null,'email9','password9','forename9','lastname9')
ON DUPLICATE KEY UPDATE SET email = 'mail9';
I cant comment, but I post this. I recommend making an external script like in python or java to do this for you by selecting * and parsing through the output because SQL itself does not have the power to do this.
I have a simple table like this
CREATE TABLE authid(
id INT NOT NULL AUTO_INCREMENT,
authid VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
Now if I insert a value with
INSERT INTO authid(authid) VALUES('test');
It will work fine and return the inserted id the first time, but if I do it again when the authid already exists (notice that we have authid marked as UNIQUE) it will return an error.
Is there a way achieve this this in one SQL statement: Insert it, get the id and if it already exists, still get the id.
Take a look at this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you're using MySQL 5.0 or higher you can use the "INSERT ... ON DUPLICATE KEY UPDATE" syntax. You may be able to combine that with LAST_INSERT_ID() (I'm not positive about that)
So:
insert into authid (authid) values ('test') on duplicate key update id=LAST_INSERT_ID(id), authid='test';
select LAST_INSERT_ID();
Well indeed if you try to insert 2 times the same value in a UNIQUE field, it won't work, that's the point of UNIQUE fields.
If I understand well, you want to know if it's possible whether to use an INSERT or an UPDATE statement depending on the existance of an item or not ? Then you need 2 queries, 1 to test existence, the other to insert new value or update existing one
Insert the value conditionally (i.e. if it doesn't exist). Whether the insert takes place or not, by the end of the statement the result will be the same: the value will be in the table. So, just select the ID of the row that matches that value. Or, speaking in SQL, like this:
INSERT INTO authid (authid)
SELECT 'test'
WHERE NOT EXISTS (
SELECT *
FROM authid
WHERE authid = 'test'
);
SELECT id
FROM authid
WHERE authid = 'test'
;
Is there a way of removing record on duplicate key in MySQL?
Say we have a record in the database with the specific primary key and we try to add another one with the same key - ON DUPLICATE KEY UPDATE would simply update the record, but is there an option to remove record if already exists? It is for simple in/out functionality on click of a button.
It's a work-around, but it works:
Create a new column and call it do_delete, or whatever, making it a tiny-int. Then do On Duplicate Key Update do_delete = 1;
Depending on your MySQL version/connection, you can execute multiple queries in the same statement. However, if not, just run a separate query immediately afterwords. Either way, the next query would just be: Delete From [table] Where do_delete = 1;. This way, if its a new entry, it will not delete anything. If it was not a new entry, it will then mark it for deletion then you can delete it.
Use REPLACE INTO:
replace into some_table
select somecolumn from othertable
will either insert new data or if thr same data exist will delete the data and insert the new one
The nearest possible solution for the same is REPLACE statement. Here is the documentation for REPLACE.
A similar question was asked on MySQL Forums and the recommended(and only) answer was to use REPLACE.
to be more clear with mySql:
values can be from same table:
replace into table1 (column1,column2) select (val1,val2) from table1
or
values can be from another table:
replace into table1 (column1,column2) select (val1,val2) from table2
or
values can be from any table with condition:
replace into table1 (column1,column2) select (val1,val2) from table1 where <br>column3=val3 and column4=val4 ...
or
also remember values can be static with table name for namesake:
replace into table1 (column1,column2) select (123,"xyz") from table1
no error will be thrown even if the update results in duplicate entry, as it will be replaced.
(remember) only autoincrement value will be increased;
and
if you have column with data-type "TIMESTAMP" with "on update CURRENT_TIMESTAMP", it will have no effect;
Yes of course there is a solutions in MySQL for your problem.
If you want to delete or skip the new inserting record if there already a duplicate record exists in the key column of the table, you can use IGNORE like this:
insert ignore into mytbl(id,name) values(6,'ron'),(7,'son');
Here id column is primary key in the table mytbl. This will insert multiple values in the table by deleting or skipping the new duplicate records.
Hope this will fulfill your requirement.
INSERT INTO table('name') VALUES("abc") IF NOT EXISTS name='abc'
If abc doesn't exist in the name column, then insert it. How can I write that query?
INSERT IGNORE INTO table(name) VALUES('abc')
This will ignore the value if it already exists. Like pjotr said, this will require name to be a unique index.
Source
Try:
insert into table('name')
select 'abc'
where not exists (select 1 from table where name='abc')
You may either use REPLACE (syntax, or, equivalent INSERT ON DUPLICATE KEY UPDATE). This is more appropriate if there's more columns and you want to update the others for the given key.
Or the IGNORE modifier (INSERT syntax) along with a unique index for the 'name' column. In that case, the insert will be ignored if it violates the unique index, but won't throw an error. That's more appropriate if you don't want to change any values and just keep the record if it already exists.
One way to do it is testing it with an IF:
IF (select count(*) from table where name = 'abc') = 0
THEN
INSERT INTO table('name') VALUES("abc")
I would enforce the column as UNIQUE and catch the exception on the code side, if you have a unicity constraint on that field. Otherwise I tend to agree with other answers.
I have Some Code...hope it will help you..
mysql_query("INSERT INTO authors (author) VALUES ('$rec_fic_author')
WHERE NOT EXISTS (SELECT * FROM authors WHERE author='$rec_fic_author')")
or die("cannot insert author");
here author is the name of table
authorID (pk)
author $rec_fic_author is _POST variable
I have a table with columns record_id (auto inc), sender, sent_time and status.
In case there isn't any record of a particular sender, for example "sender1", I have to INSERT a new record otherwise I have to UPDATE the existing record which belongs to "user1".
So if there isn't any record already stored, I would execute
# record_id is AUTO_INCREMENT field
INSERT INTO messages (sender, sent_time, status)
VALUES (#sender, time, #status)
Otherwise I would execute UPDATE statement.
Anyway.. does anyone know how to combine these two statements in order to insert a new record if there isn't any record where the field sender value is "user1" otherwise update the existing record?
MySQL supports the insert-on-duplicate syntax, f.e.:
INSERT INTO table (key,col1) VALUES (1,2)
ON DUPLICATE KEY UPDATE col1 = 2;
If you have solid constraints on the table, then you can also use the REPLACE INTO for that. Here's a cite from MySQL:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
The syntax is basically the same as INSERT INTO, just replace INSERT by REPLACE.
INSERT INTO messages (sender, sent_time, status) VALUES (#sender, time, #status)
would then be
REPLACE INTO messages (sender, sent_time, status) VALUES (#sender, time, #status)
Note that this is a MySQL-specific command which doesn't occur in other DB's, so keep portability in mind.
As others have mentioned, you should use "insert...on duplicate key update", sometimes referred to as an "upsert". However, in your specific case you don't want to use a static value in the update, but rather the values you pass in to the values clause of the insert statement.
Specifically, I think you want to update two columns if the row already exists:
1) sent_time
2) status
In order to do this, you would use an "upsert" statement like this (using your example):
INSERT INTO messages (sender, sent_time, status)
VALUES (#sender, time, #status)
ON DUPLICATE KEY UPDATE
sent_time = values(sent_time),
status = values(status);
Check out "Insert on Duplicate Key Update".
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
One options is using on duplicate update syntax
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Other options is doing select to figure out if record exists and then doind inser/update accordingly. Mind that if you're withing transaction select will not explicitly terminate the transaction so it's safe using it.
use merge statement :
merge into T1
using T2
on (T1.ID = T2.ID)
when matched
then update set
T1.Name = T2.Name
when not matched
then insert values (T2.ID,T2.Name);