views:

331

answers:

4

If I set a database column as an autonumber primary key field, will the autonumbering feature prevent those values from being modifiable?

Or does the primary key nature of the column make it unmodifiable?

Both? Neither?

+2  A: 

Neither. You can modify it all you want. Setting a column as autoincrement just specifies the default value for new rows, that's it. After that it acts just like a normal column.

EDIT: Apparently this isn't true for SQL Server, but you didn't specify so I just went with the popular answer.

musicfreak
+2  A: 

As always, it depends on your database. However, the answer is probably neither.

In SQL Server, you are restricted from inserting primary keys manually into an identity column, unless you use the following:

SET IDENTITY_INSERT [dbo].[MyTable] ON
INSERT INTO [dbo].[MyTable] (id, name) VALUES (1000, 'Foo')
SET IDENTITY_INSERT [dbo].[MyTable] OFF
Dave Bauman
I thought this would be a fairly database-agnostic issue. Surprised.
eggdrop
There's a comparison of common databases here: http://troels.arvin.dk/db/rdbms/#mix-identity
Dave Bauman
+1  A: 

Did you mean auto-increment?

In MS-Sql no,
In mysql yes (may depend on engine)

Sharique
Auto-increment, yes.
eggdrop
+1  A: 

It's not DB-agnostic. However, MySQL and SQLite (for example) allow you to modify autoincrement primary keys:

mysql:

create table foo (id INTEGER AUTO_INCREMENT, PRIMARY KEY(id));
insert into foo values (null);
select * from foo;
update foo set id = 2 where id = 1;
select * from foo;

sqlite (see http://www.sqlite.org/faq.html#q1 for what AUTOINCREMENT actually means):

create table foo(id INTEGER PRIMARY KEY AUTOINCREMENT);
insert into foo VALUES(null);
select * from foo;
update foo set id = 2 where id = 1;
select * from foo;
Matthew Flaschen