0

I have a SQL syntax error with my IF NOT EXISTS on line 1 when I tried to do this request on MySQL, and I can't figure why.

IF NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn')
BEGIN
INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
END;

I'm trying to insert first_name only if there is no other same first name in my_table.

I also tried this syntax, but I still have the error 1064 "You have an error in your SQL syntax" :

IF NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn') THEN
INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
END IF;

I tried SELECT * FROMmy_tableWHERE first_name = 'Testfn' separately, and it works.

And like this doesn't work too :

INSERT INTO `my_table` (first_name)
VALUES ('Testfn')
WHERE NOT EXISTS (SELECT * FROM `my_table` WHERE first_name = 'Testfn');

EDIT : first_name is UNIQUE in the database.

Emilie
  • 658
  • 1
  • 9
  • 20

1 Answers1

0

You have not need to write a column name, without specifying you can try to insert because we already checked condition on above. So basically you can do it using Merge Statement like.

MERGE INTO my_table
USING ( 
   SELECT first_name
) t
ON t.first_name = my_table.first_name
WHEN NOT MATCHED THEN 
INSERT (first_name) VALUES (t.first_name);

Hope this help you!

Jay Patel
  • 23,885
  • 12
  • 63
  • 74