0

I want to insert values into a table but need to check if the value exist in the last row or not. I normally insert values like

INSERT INTO `table` (`column1`,`column2`,`column3`,`column4`) VALUES ('value1','value2','value3','value4')

But now I need to put a check, if the value1 exist in the last row of the table do not insert, insert otherwise.

For that I am trying to use

WHERE NOT EXISTS

I actually want to check the last row of the table if the value exist then it should not duplicate it.

Jason Sturges
  • 15,635
  • 14
  • 56
  • 75
AL̲̳I
  • 2,269
  • 4
  • 25
  • 44

4 Answers4

1

You can state explicitly what happens when the primary key for a table already exists. Example:

INSERT INTO table (...) VALUES (...) ON DUPLICATE KEY UPDATE
0xCAFEBABE
  • 5,280
  • 5
  • 30
  • 54
  • Thanks for the reply!!!! I actually want to check the last row of the table if the value exist then it should not duplicate it. – AL̲̳I Jun 01 '12 at 08:59
  • this is definitely the right answer that you are looking for. – neo Jul 10 '12 at 12:43
0

Alias the sub select. It is mandatory in MySQL.

Jeff Watkins
  • 6,243
  • 13
  • 17
  • INSERT INTO tableName(column1, column2, column3, column4) SELECT value1,value2,value3,value4 FROM tableName WHERE NOT EXISTS (SELECT * FROM tableName m2 WHERE m2.column1 = value1 AND m2.column2 = value2); Are you talking about something like this??? – AL̲̳I Jun 01 '12 at 09:09
0

as an aside, as per the documentation, in the WHERE NOT EXISTS select, you don't need to specify fields (value1, value2, in your case) because that is entirely ignored. So just use *

In any event, I believe this will answer your question: How to 'insert if not exists' in MySQL?

Community
  • 1
  • 1
Yevgeny Simkin
  • 26,055
  • 37
  • 127
  • 228
0

Adding an unique constraint on the pair (column 1, column 2) isn't a better way to do that ?

Idaho
  • 1,055
  • 7
  • 8
  • except for when the attempted insert will cause an error that your code isn't prepared to handle... otherwise, yeah, I'd say that's the best approach. – Yevgeny Simkin Jun 01 '12 at 08:43