44

Can I make a field AUTOINCREMENT after made a table? For example, if you create a table like this:

create table person(id integer primary key, name text);

Then later on realise it needs to auto increment. How do I fix it, ie in MySQL you can do:

alter table person modify column id integer auto_increment

Is table creation the only opportunity to make a column AUTOINCREMENT?

2
  • 3
    do you get the solution? Nov 7, 2014 at 5:45
  • Try inserting into the table and with name only and you'll see it increments automatically based on INTEGER PRIMARY KEY- insert into person (name)values ('Bob');
    – dataman
    Jul 29 at 13:31

11 Answers 11

53

You can dump the content to a new table:

CREATE TABLE failed_banks_id (id integer primary key autoincrement, name text, city text, state text, zip integer, acquired_by text, close_date date, updated_date date);

INSERT INTO failed_banks_id(name, city, state, zip, acquired_by,close_date, updated_date)
SELECT name, city, state, zip, acquired_by,close_date, updated_date
FROM failed_banks;

And rename the table:

DROP TABLE failed_banks;
ALTER TABLE failed_banks_id RENAME TO failed_banks;
3
  • Simplicity it's always the best option. Thank you. Nov 4, 2019 at 16:37
  • 2
    Make sure to also insert the id column from the old table, in case some rows were removed. Otherwise, since the ids will be regenerated consecutively, any links from other tables using id as key will point to wrong rows in the new table.
    – Mike
    Dec 2, 2019 at 17:31
  • 1
    Works. The limitations of sqlite are simply ridiculous. Apr 9, 2020 at 15:09
13

Background:

The new key will be unique over all keys currently in the table, but it might overlap with keys that have been previously deleted from the table. To create keys that are unique over the lifetime of the table, add the AUTOINCREMENT keyword to the INTEGER PRIMARY KEY declaration.

http://www.sqlite.org/faq.html#q1

SQLite limitations:

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

http://www.sqlite.org/lang_altertable.html

Hack seems to exist:

It appears that you can set

PRAGMA writable_schema=ON;

Then do a manual UPDATE of the sqlite_master table to insert an "id INTEGER PRIMARY KEY" into the SQL for the table definition. I tried it and it seems to work. But it is dangerous. If you mess up, you corrupt the database file.

http://www.mail-archive.com/sqlite-users@sqlite.org/msg26987.html

1
  • It is less dangerous if you do it by the export (dump) and re-import method.
    – Jay
    Feb 19, 2013 at 3:47
7

Simplest way — Just export and re-import

It is possible, and relatively easy. Export the database as an sql file. Alter the SQL file and re-import:

  sqlite3 mydata.db .dump > /tmp/backup.sql
  vi /tmp/backup.sql
  mv mydata.db mydata.db.old
  sqlite3 mydata.db
  sqlite>.read /tmp/backup.sql
3
  • this does not work for autoincrement columns - at least for me, inserting a value into an autoincrement column makes that row unreadable Aug 5, 2013 at 12:51
  • this also requires an administrative, manual operation for only server scenarios. If the db is installed on each client, you cant execute this from the code,
    – Zig Mandel
    Aug 26, 2015 at 19:19
  • Worked very fine for me. I've replaced "id" int(11) NOT NULL with "id" integer primary key autoincrement and removed PRIMARY KEY ("id") line at .sql file.
    – quasiyoke
    Apr 11, 2016 at 3:28
6

From the SQLite Faq

Short answer: A column declared INTEGER PRIMARY KEY will autoincrement

So when you create the table, declare the column as INTEGER PRIMARY KEY and the column will autoincrement with each new insert.

Or you use the SQL statment ALTER to change the column type to an INTEGER PRIMARY KEY after the fact, but if your creating the tables yourself, it's best to do it in the initial creation statement.

7
  • 4
    Its all well and good to say "do it at the initial creation statement", the question is how do you fix it if you have already done the initial creation statement.
    – Jay
    Feb 19, 2013 at 3:46
  • up for: A column declared INTEGER PRIMARY KEY will autoincrement
    – nebula
    Sep 25, 2014 at 13:40
  • 4
    It's correct to say that INTEGER PRIMARY KEY columns will automatically increment on insert. It's more correct to say that such columns are an alias for the ROWID column, a 64 bit integer key that exists on most tables. Furthermore using the AUTOINCREMENT keyword when defining those columns will change the increment behavior so that values are never recycled. All of that to say, this answer doesn't really address the core of the question which is about altering an existing table. Oct 12, 2014 at 23:06
  • Thanks god. This auto-autoincrement saved my day. Apr 13, 2015 at 13:59
  • 3
    Depend on which autoincrement behaviour one is looking. If AUTOINCREMENT is not specified, it will still auto increment but will reuse deleted keys. If you want the key to be unique across the lifetime of the table, one has to specify AUTOINCREMENT. Yes it is confusing and this answer does not explain clearly this concept so it might mislead some people.
    – Bruce
    Aug 27, 2016 at 3:49
4

You can do it with SQLite Expert Personal 4:

1) Select the table and then go to "Design" tab > "Columns" tab.

2) Click "Add" and select the new column name, and type INTEGER and Not Null > Ok.

3) Go to "Primary Key" tab in "Desgin tab". Click "Add" and select the column you just created. Check the "Autoincrement" box.

4) Click "Apply" on the right bottom part of the window.

If you go back to the "Data" tab, you will see your new column with the autogenerated numbers in it.

2

You cannot alter columns on a SQLite table after it has been created. You also cannot alter a table to add an integer primary key to it.

You have to add the integer primary key when you create the table.

2

While the Sqlite site gives you an example how to do it with a table with only a three fields, it gets nasty with one of 30 fields. Given you have a table called OldTable with many fields, the first of which is "ID" filled with integers. Make a copy of your database for backup. Using the command program dot commands,

    .output Oldtable.txt
    .dump Oldtable
    Drop Table Oldtable;

Open Oldtable.txt in Microsoft Word or a grep like text editor. Find and Replace your Integer field elements with NULL.(You may need to adjust this to fit your fields). Edit the Create Table line so the field that was defined as Integer is now INTEGER PRIMARY KEY AUTOINCREMENT. Save as NewTable.txt

Back in the command program dot

   .read NewTable.txt

Done. ID is now autoincrement.

1

Yes Do you have phpmyadmin installed? I believe if you go to the 'structure' tab and look along the right columnn (where the field types are listed) - I think you can change a setting there to make it autoincrement. There is also a SQL query that will do the same thing.

1

Yes, you can make a column which is autoincrement. Modify the table and add a column. Keep in mind that it is of type INTEGER Primary Key.

0

you can alter the table, altering the column definition

-5

Simple Answer is as below,

CREATE TABLE [TEST] (
  [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
  [NAME] VARCHAR(100));

and you are done.

1
  • 3
    didn't read the question. it's how to add an autoincrement /after/ the table is created.
    – Kae Verens
    Dec 21, 2011 at 22:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.