13

Is there a query that will just check for the record and if it doesn't exists insert? I don't want to on duplicate update or replace. Looking for a one query solution, looked at other answer but not really what I was hoping for.

Table:

name|value|id
------------------
phill|person|12345

pseudo query:

IF NOT EXISTS(name='phill', value='person', id=12345) INSERT INTO table_name
2
  • 1
    Can you clarify the question a bit? Is id the only unique field? (in a quick and dirty way you could use a unique index and it will fail if you try and insert a row with a duplicate value). Do the name and value have to be unique as well? Commented Feb 8, 2010 at 17:07
  • all three values are unique and must not be empty. Id has an index, the name and value should be different as well but the id is a must Commented Feb 8, 2010 at 17:13

2 Answers 2

17

Use 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.

http://dev.mysql.com/doc/refman/5.0/en/replace.html

-- For your example query
REPLACE INTO table_name(name, value, id) VALUES
('phill', 'person', 12345) 

Edit: Since you can't use REPLACE another option is to: set constraint indexes for the table data (primary key, uniqueness) and use INSERT IGNORE

INSERT IGNORE INTO table_name
SET name = 'phill',
    value = 'person',
    id = 12345;
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I understand the functionality but my user only has access to SELECT, INSERT, UPDATE. but I'm trying to stay away from UPDATE and I don't know if I have permission for the REPLACE function
does the INSERT IGNORE delete and add the record again? or does it just skip it if found and insert if not found?
2

How about doing an insert from a select query which has a sub-query to only return a row if the row does not already exist?

Pseudocode:

INSERT INTO TABLE_FOO (...)
SELECT @VAR1, VAR2 ...
FROM DUMMYTABLE -- THIS TABLE SHOULD CONTAIN 1 RECORD OF ANYTHING
                -- IN CASE THE FROM IS REQUIRED
WHERE (SELECT COUNT(*) FROM TABLE_FOO WHERE COLUMN1 = @VAR1) = 0

This pattern should work, you'll just need to get the syntax correct for MySQL.

1 Comment

This was useful when dealing with rows that didn't use keys or uniques.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.