3

Given a table employee with columns ID(pk) and name

ID|name
--+-----
1 |John
2 |James
3 |Tom

Can I do

INSERT INTO employee (name) VALUES (Jack);

and somehow have the database auto assign the next available ID? Can a trigger do it? If so, how?

user299648
  • 2,769
  • 6
  • 34
  • 43

3 Answers3

2

You want auto increment column. You can refer to the documentation here: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

dcp
  • 54,410
  • 22
  • 144
  • 164
2

You can use the AUTO INCREMENT Feature in My Sql. When you create the table, you can do something like this:

CREATE TABLE employee(
 id MEDIUMINT NOT NULL AUTO_INCREMENT,
 name CHAR(30) NOT NULL,
 PRIMARY KEY (id)
) ENGINE=MyISAM;

Or May be use the alter table Query to modify the column ID to have auto incremented values

reggie
  • 13,313
  • 13
  • 41
  • 57
1

Create your table with an identity autoincrement column:

CREATE TABLE table_name
(
   id INTEGER AUTO_INCREMENT PRIMARY KEY,
   -- other columns to follow
)
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Chad
  • 18,706
  • 4
  • 46
  • 63