Creating a Sequence Column and Generating Sequence Values
Problem
You want to include a sequence column in a table.
Solution
Use an
AUTO_INCREMENT
column.
Discussion
This section provides the basic background on how AUTO_INCREMENT
columns work, beginning with
a short example that demonstrates the sequence-generation mechanism.
The illustration centers around a bug-collection scenario: your son
(eight-year-old Junior) is assigned the task of collecting insects for
a class project at school. For each insect, Junior is to record its
name (“ant,”
“bee,” and so forth), and its
date and location of collection. You have expounded the benefits of
MySQL for record-keeping to Junior since his early days, so upon your
arrival home from work that day, he immediately announces the
necessity of completing this project and then, looking you straight in
the eye, declares that it’s clearly a task for which MySQL is
well-suited. Who are you to argue? So the two of you get to work.
Junior already collected some specimens after school while waiting for
you to come home and has recorded the following information in his
notebook:
Name | Date | Origin |
---|---|---|
millipede | 2006-09-10 | driveway |
housefly | 2006-09-10 | kitchen |
grasshopper | 2006-09-10 | front yard |
stink bug | 2006-09-10 | front yard |
cabbage butterfly | 2006-09-10 | garden |
ant | 2006-09-10 | back yard |
ant | 2006-09-10 | back yard |
millbug | 2006-09-10 | under rock |
Looking over Junior’s notes, you’re pleased to see that even at his tender age, he has learned to write dates in ISO format. However, you also notice that ...
Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.