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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

what if I have 3 rows to add?
Check I Edited My answer
I get this: Error Code: 1267. Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation '='
I'm using Mysql 5.7.21
Run Below Query and then try SET collation_connection = 'utf8_general_ci'; ALTER TABLE account_types CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.