Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql -- inserting in table with only an auto incrementing column

Tags:

mysql

Lets say we have table A with just one column, id(which is the primary key)

How do we insert a new row into the table without specifying an id?

I tried this

INSERT INTO A (`id`) VALUES (NULL)

and it doesn't work

Edit: I forgot to mention that id, the primary key has the auto_increment and NOT NULL attribute.

Edit 2: The exact error when running the query above is

Column 'id' cannot be null
like image 948
developarvin Avatar asked May 11 '11 09:05

developarvin


People also ask

Can you insert into auto increment field MySQL?

Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How do I make a column auto increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

How do I add an auto increment to an existing table?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

Why is my auto increment not working in MySQL?

Basically this is a bug in MySQL that causes the problem but a work around is simple. The problem happens when the Auto-Increment value of a table grows beyond the limit. Just run this SQL query in MySQL to fix the bug.


2 Answers

As soon as 'id' as the auto-increment enable (assuming ID is an integer), you can just do:

INSERT INTO A (id) values (null)

and 'id' will keep incrementing each time.

like image 103
Sebastien Avatar answered Oct 24 '22 18:10

Sebastien


only works if you're using an auto_increment primary key (PK) as every PK must have a unique, non null value.

drop table if exists A;
create table A
(
id int unsigned not null auto_increment primary key
)
engine=innodb;

insert into A (id) values (null),(null);

mysql> select * from A order by id;
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)
like image 44
Jon Black Avatar answered Oct 24 '22 19:10

Jon Black