Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO table IF table exists otherwise CREATE TABLE

Do mysql support something like this?

INSERT INTO `table` VALUES (NULL,"1234") IF TABLE EXISTS `table` ELSE CREATE TABLE `table` (id INT(10), word VARCHAR(500));

2 Answers

I'd create 2 statements. Try this:

CREATE TABLE IF NOT EXISTS `table` (
id INT(10),
word VARCHAR(500)
);
INSERT INTO `table` VALUES (NULL,"1234");
like image 98
imjoris Avatar answered Jun 14 '26 01:06

imjoris


You can first check if the table exists, if it doesn't then you can create it. Do the insert statement after this..

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Something like

CREATE TABLE IF NOT EXISTS table (...)

INSERT INTO table VALUES (...)

Note:

However, there is no verification that the existing table has a structure identical to that indicated by the CREATE TABLE statement.

like image 30
GercoOnline Avatar answered Jun 14 '26 01:06

GercoOnline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!