MySQL create table if not exists and insert record only if table was created

Combine the creation and insert into a single statement:

CREATE TABLE IF NOT EXISTS tableName (
    id int(9) NOT NULL, 
    col1 int(9) DEFAULT NULL, 
    col2 int(3) unsigned zerofill DEFAULT NULL,
    PRIMARY KEY(id)
)  ENGINE = InnoDB DEFAULT CHARSET = latin1
AS SELECT 1 AS id, 10 AS col1, 5 AS col2;

If it doesn’t create the table, AS SELECT ... clause is ignored.

Leave a Comment