insert - where not exists - mysql

I would like to insert a record into a table if a record doesnt exist already exist with that domain name. The following SQL should achieve this but is getting an error.
The reason I want to do the update first is because I am doing multiple updates later in my code and need the record in my table first before doing all of the updates.
Why am I getting an error on this mySQL query?
insert into domain (name)
values ('domain.com.au')
WHERE NOT EXISTS
(
select name
from domain
where name = 'domain.com.au'
);
Both queries when split work fine but when together do not.

Let your database handle it for you. Use a unique index on name and your INSERT will fail if you try to insert a duplicate.
CREATE UNIQUE INDEX idx_name ON domain (name)

You cannot combine WHERE with INSERT clause. Use REPLACE INTO instead.

What error are you getting?
My guess would be the that the select inside the 'where not exists' is not allowed.

Related

Database INSERT INTO SET ... WHERE(SELECT ...)

I am trying to insert my values into table if Admin_User_Role_Id value against Admin_Id is not present in the table. Is it possible to insert!
My Table Structure:
Admin_User_Id (FK)
Admin_User_Role_Id (FK)
Is_Enabled (boolean flag)
Query which I tried, but not success
INSERT INTO role_association
SET Admin_User_Id=61, Admin_User_Role_Id=2, Is_Enabled=0
WHERE Admin_User_Role_Id
NOT IN
(SELECT Admin_User_Id, Admin_User_Role_Id FROM role_association)
I think it is possible but my logic is wrong. How should I manage this query to work successfully!
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
Probably you take care about where condition in your programming logic and write a simple insert statement and the depending on your logic use this statement to insert the records. Hope you got my point.
You want to insert your values in your table using this query for your reference
INSERT INTO Yourtablename(column1,column2,column3,...)
VALUES ('value1','value2','value3',.....);
You want to ADD one new column in your table means using this query
** ALTER TABLE table_name ADD column_name datatype**

Web SQL - Insert if not exists or Unique column?

I try to execute insert or ignore into WDCategory(name,userID) values('Cate 1',1) which name is a unique column but not successful if there is a record with same name in the table. "Not Successful" means that the query fail instead of execute and insert nothing. I have try insert into WDCategory(name,userID) values('Cate 1',1) If Not Exists but nothing change.
Update: I try
insert or replace into WDCategory(name,userID) values('Cate 1',1)
it works. But the record now have a new id (auto increase). Is there any way to keep the old values?
Please help!

MySQL insert on duplicate key; delete?

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.

How do I make a MySQL insert query that "inserts if not exists"?

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

Access Auto-Increment Value During INSERT INTO Statement

I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.
I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.
Thanks in advance.
I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.
Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:
UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();