Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I have a table with only an auto-increment column, how do I insert into it?

A colleague asked me, if you have a table in SQL Server with only an auto-increment column, how do you insert a new row into that table?

INSERT INTO MyTable() VALUES()

...doesn't work.

As for why... I'm not really sure. But I found the question kind of compelling.

like image 560
Scott Whitlock Avatar asked Jun 30 '09 19:06

Scott Whitlock


People also ask

Can you INSERT into auto increment?

You can insert into an auto-increment column and specify a value. This is fine; it simply overrides the auto-increment generator. If you try to insert a value of NULL or 0 or DEFAULT , or if you omit the auto-increment column from the columns in your INSERT statement, this activates the auto-increment generator.

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

Here's the syntax of ALTER TABLE statement, ALTER TABLE table_name MODIFY column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY; In the above statement, you need to specify the table_name and column_name. Here's the SQL statement to add AUTO INCREMENT constraint to id column.

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.

Can we use auto increment without primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.


2 Answers

insert into mytable default values
like image 162
zinglon Avatar answered Oct 11 '22 02:10

zinglon


Apparently this works:

INSERT INTO MyTable DEFAULT VALUES

(Just discovered it after I hit Ask Question. Sorry!)

like image 40
Scott Whitlock Avatar answered Oct 11 '22 02:10

Scott Whitlock