Execute INSERT if table is empty? Execute INSERT if table is empty? sql sql

Execute INSERT if table is empty?


Use SELECT instead of VALUES to be able to expand the query with a WHERE clause.

EXISTS is a better & faster test than COUNT

INSERT INTO my_table (colname)SELECT 'foo'WHERE NOT EXISTS (SELECT * FROM my_table)


One way would be to place a unique key on a column. Then execute a REPLACE:

REPLACE [LOW_PRIORITY | DELAYED]    [INTO] tbl_name [(col_name,...)]    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted


This is easier to read:

INSERT INTO my_table (colname) SELECT 'foo' FROM DUALWHERE NOT EXISTS (SELECT * FROM my_table);

The lack of a VALUES is mitigated by the SELECT FROM DUAL which will provide the values. the FROM DUAL is not always required, but it doesn't hurt to include it for that weird configurations where it is required (like the installation of Percona I am using).

The NOT EXISTS is faster than doing a count which can be slow on a table with a large number of rows.