tags:

views:

136

answers:

3

I have this table:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)


1. insert into persons values (1, 'John', 'Smith', 'LA', 'LA');
2. insert into persons (p_id, lastname, firstname, address, city) values  (2, 'John', 'Smith', 'LV', 'LV');

How can I insert data into a table, without specifying a value for a primary key (the primary key doesn't have the "auto_increment" attribute).

I tried with:

  1. insert into persons values ('John', 'Smith', 'LA', 'LA');
  2. insert into persons values (null, 'John', 'Smith', 'LA', 'LA');
  3. insert into persons values (auto, 'John', 'Smith', 'LA', 'LA');

but no luck

+3  A: 

Primary keys cannot be null, and if you don't set them to auto increment, then how does MySQL know what you want to put in the table? You need to either specify the ID (perhaps by selecting the MAX(P_Id) and adding 1 to it) or set it to auto increment.

Although simply adding an auto increment field is definitely the best approach, you could try something like this:

INSERT INTO Persons (P_Id, FirstName, LastName, Address, City)
VALUES ((SELECT MAX(P_Id) + 1 FROM Persons), 'John', 'Smith', 'LA', 'LA');

This uses a subselect, so if you're using an old version of MySQL it may not work.

Scott Anderson
Thank you for the answer!
cc
A: 

I have seen this implemented as

  • DEFAULT value on the PK column (say -9999)
  • A table that holds the Current_PK value
  • An INSERT trigger that changes that PK from -9999 to Current_PK and increments Current_PK

Another way that I have seen is to get the MAX from the table and increment it and put it into the new row.

I must say, that both these methods caused bad data, caused locking and blocking and degraded performance.

In your case, I do not see a way other than actually specifying a value for PK.

Raj More
Ok, so there is not a secret trick. :))Thanx a lot!
cc
At a place where I worked, we had a table of these primary keys ( tablename, nextkey ) tuples. One day somebody did an UPDATE intending to update one key's value but run the query forgetting the WHERE clause. Suffice to say it took several hours to get things straightened out!
Bob Kaufman
A: 

Select p_id+1 From Person OrderBy p_id desc limit 1;

Joe Tuskan