2

i want to set query if row not exist

IF NOT EXISTS (SELECT id FROM table WHERE id=1)
INSERT INTO table (id, name) VALUES (1,'abx');

and that if id!=1 then values are inserted and Check if row already exists

if any solution ?

thanks in advance ...

finally i soved it

INSERT INTO table (id, name) VALUES (1,'abx') ON DUPLICATE KEY UPDATE id = 1;

thanks for your suport

4 Answers4

1

You have problem with data types - in SELECT id is compared to number (id = 1 - without apostrophes) and in INSERT id is written as a string (in apostrophes: '1').

psur
  • 4,113
  • 23
  • 34
1
INSERT IGNORE INTO `table_name` (`id`, `name`)
VALUES (1, 'abx');
Alex Pliutau
  • 19,672
  • 26
  • 103
  • 139
1

MySQL does not have "IF NOT EXISTS".

For more info: How to 'insert if not exists' in MySQL?

You'll see that there are workarounds, but using MsSQL syntax won't work.

Using IGNORE should help: INSERT IGNORE INTO

Alternatively, simply let it fail.

Community
  • 1
  • 1
Tom van der Woerdt
  • 28,143
  • 7
  • 67
  • 105
0

I think that:

INSERT IGNORE INTO table (id, name) VALUES (1,'abx');

does that you want. It'll fail silently if the INSERT was unsuccessful.

Note that the key doesn't need quotes, it's an integer, not a string

James C
  • 13,501
  • 1
  • 32
  • 42