Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute INSERT if table is empty?

Tags:

sql

mysql

Is there a way to do an insert under a count condition, something like:

INSERT INTO my_table (colname) VALUES('foo') IF COUNT(my_table) < 1

Basically I want to insert a single default record if the table is currently empty. I'm using mysql.

like image 884
user291701 Avatar asked Mar 15 '11 03:03

user291701


People also ask

Which function check if table is empty?

The recommended way to check whether a table variable or table is empty is to use the predicate IS_EMPTY.

How do you insert if not exists?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

How do you insert an empty value in a table?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL); To understand the above syntax, let us first create a table.


1 Answers

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)
like image 162
RichardTheKiwi Avatar answered Sep 22 '22 23:09

RichardTheKiwi