| SQL - Questions and Answers Have a SQL question? Post it here. First do a search to see if someone hasn't already answered it. |
|
||||||
![]() |
|
|
LinkBack (2) | Thread Tools | Search this Thread |
Rating:
|
|
|||
|
MySQL has a special construct for this. Assume the 'username' column below is UNIQUE:
INSERT INTO users (username, email) VALUES ('Jo', 'jo@email.com')The 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns. |
|
|||
|
How about this:
IF (EXISTS (SELECT * FROM AA_TestTable AS t1 |
|
|||
INSERT INTO users (username)I use this method a lot. Obviously, 'Jo' would usually either be a variable or a field selected from another table. |
|
|||
|
This opption worked wonders! Thanks for posting
|
|
|||
|
Quote:
You should be VERY CAREFUL with things like this. If you can't afford to set the transaction isolation level to SERIALIZABLE, some other transaction could add the row with ord_num='FFF' after you've tested for its existence, but before you've inserted it. This way you end up with violated primary constraint and error in one of these transactions. |
|
|||
|
This is a variation that works for tables with multiple primary keys.
If you have a users table with columns of username, dept, and age, and primary keys of username and dept, then this will only insert a user if it doesn't exist already.
INSERT INTO users (username, dept, age) SELECT username='mp', dept='tax', age=5 WHERE (SELECT COUNT (*) FROM users WHERE username='mp' AND dept='tax')=0;I initially found this syntax confusing, but here's how I 'parsed' it. This part returns 0 if it doesn't exist: SELECT COUNT (*) FROM users WHERE username='mp' AND dept='tax' This part creates a record-like row with static values and represents the record to insert: SELECT username='mp', dept='tax', age=5 The WHERE-clause following the above part will only return the value to insert if the count is 0. |
![]() |
| Thread Tools | Search this Thread |
| Rate This Thread | |
|
|
LinkBacks (?)
LinkBack to this Thread: http://www.sqlrecipes.com/sql_questions_answers/insert_update_record_if_already_exists-6/
|
|||
| Posted By | For | Type | Date |
| CreativeNRG's bookmarks tagged with | This thread | Refback | 09-03-2007 06:46 AM |
| Pages tagged with | This thread | Refback | 08-30-2007 07:29 PM |