1

I have a table named batch1 with just one column in it id which is primary key.

I can insert data into it with following query.

INSERT INTO batch1 VALUES(NULL); 

Now I need to set limit on records for this table so it may only insert required number of rows. For example say if limit is set 1000, the above table must not insert more records above that and give error.

I am storing limit in other table. What are my option other than LOCKS?

1

2 Answers 2

2

Building on Andomar's answer, which throws a syntax error for my version of MySQL:

insert into batch1 (id) select null from ( select count(*) as num from batch1 ) as counted where counted.num < 1000; 

This selects from a derived table, using the result to return either one or zero rows from the outer select.

Sign up to request clarification or add additional context in comments.

4 Comments

MySQL's primary key handling enforces uniqueness. This query simply inserts NULL as the id, just like your example query does. For that to work at all (more than once, anyway), the column needs to be set as AUTO_INCREMENT. There are situations where an AUTO_INCREMENT column can re-use values previously deleted from the table, but it will never insert a value that currently exists.
Got it. What if I want to get the last inserted id? I can use LAST_INSERT_ID() but that also returns when the INSERT didn't work.
You could check both last_insert_id() and row_count(). In one query: select id from (select last_insert_id() as id) as subq where row_count() > 0;
Because I was executing dynamic query, row_count was always 0. Fixed it and it's working. I am not sure why we need to deallocate variables in MySQL.
0

You could use a where clause to prevent unwanted updates:

insert into batch1 select null where ( select count(*) from batch1 ) < 1000 

You can test with row_count whether the update got through:

select row_count() as InsertedRecords; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.