Search code examples
mysqlsqlsql-insertcreate-table

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


I need to create a table and insert a first record only if the table was just newly created.

I do create the table with this 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;

How do I insert an first record only if the table was just created?


Solution

  • 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.