2

I want to insert some data on my table if the table is empty (0 rows).

I tried this:

IF NOT EXISTS(SELECT 1 FROM `account_types`)
THEN
       INSERT INTO `account_types` (`type`, `group`) VALUES ('400', 'test');
       INSERT INTO `account_types` (`type`, `group`) VALUES ('401', 'test2');
END IF;

But I get

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(SELECT 1 FROM account_types) THEN INSERT INTO `account_types' at line 1

What can I do ? I'm using MYSQL

  • Possible duplicate of [Execute INSERT if table is empty?](https://stackoverflow.com/questions/5307164/execute-insert-if-table-is-empty) – Vatev Apr 20 '18 at 13:19

1 Answers1

1
INSERT INTO `account_types`(`type`, `group`)
SELECT * FROM
(SELECT '400' `type`, 'test' `group` UNION ALL
 SELECT '401' `type`, 'test2' `group` UNION ALL
 SELECT '402' `type`, 'test3' `group`) A
WHERE NOT EXISTS (SELECT NULL FROM account_types B WHERE A.type=B.type);

Demo

http://sqlfiddle.com/#!9/d1e80e/1

Jay Shankar Gupta
  • 5,707
  • 1
  • 7
  • 26