Recipe 11.9. Starting a Sequence at a Particular Value


Problem

Sequences start at 1, but you want to use a different starting value.

Solution

Add an AUTO_INCREMENT clause to your CREATE TABLE statement when you create the table. If the table has already been created, use an ALTER TABLE statement to set the starting value.

Discussion

By default, AUTO_INCREMENT sequences start at one:

mysql> CREATE TABLE t     -> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> SELECT id FROM t ORDER BY id; +----+ | id | +----+ |  1 | |  2 | |  3 | +----+ 

For MyISAM or InnoDB tables, you can begin the sequence at a specific initial value n by including an AUTO_INCREMENT = n clause at the end of the CREATE TABLE statement:

mysql> CREATE TABLE t     -> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))     -> AUTO_INCREMENT = 100; mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> SELECT id FROM t ORDER BY id; +-----+ | id  | +-----+ | 100 | | 101 | | 102 | +-----+ 

Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE:

mysql> CREATE TABLE t     -> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)); mysql> ALTER TABLE t AUTO_INCREMENT = 100; mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> SELECT id FROM t ORDER BY id; +-----+ | id  | +-----+ | 100 | | 101 | | 102 | +-----+ 

To start a sequence at n for storage engines other than MyISAM or InnoDB, you can use a trick: insert a "fake" row with sequence value n -1, and then delete it after inserting one or more "real" rows. The following example illustrates how to start a sequence at 100 for a BDB table:

mysql> CREATE TABLE t     -> (id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))     -> ENGINE = BDB; mysql> INSERT INTO t (id) VALUES(99); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> INSERT INTO t (id) VALUES(NULL); mysql> DELETE FROM t WHERE id = 99; mysql> SELECT * FROM t ORDER BY id; +-----+ | id  | +-----+ | 100 | | 101 | | 102 | +-----+ 

Remember that if you empty a table completely with TRUNCATE TABLE, the sequence may be reset to begin with 1, even for storage engines that normally do not reuse sequence values (Section 11.3). In this case, you should reinitialize the sequence value explicitly after clearing the table if you don't want it to begin with 1.




MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2004
Pages: 375
Authors: Paul DuBois

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net