![]() |
![]() |
Free Books / Computers / Practical PostgreSQL / | ![]() |
|
![]() |
||||
![]() |
![]() |
|||
![]() |
![]() |
|||
![]() |
||||
|
|
||||
![]() |
![]() |
|||
![]() |
The serial type |
![]() |
||
![]() |
||||
![]() |
![]() |
![]() |
||
![]() |
||||
This section is from the "Practical PostgreSQL" book, by John Worsley and Joshua Drake. Also available from Amazon: Practical PostgreSQL.
The serial type is non-standard, but useful, shortcut which allows you to easily create unique identifier columns within tables. It literally combines the functionality of a 4-byte integer data type, an index and a sequence.
In fact, as of the writing of this book, the two methods illustrated in Example 3-26 are functionally identical.
Example 3-26. Using the serial Data Type
booktown=# -- First, implicitly create the sequence
booktown=# -- and index via the serial type.
booktown=#
booktown=# CREATE TABLE auto_identified (id serial);
NOTICE: CREATE TABLE will create implicit sequence 'auto_identified_id_seq' for SERIAL column 'auto_identified.id'
NOTICE: CREATE TABLE/UNIQUE will create implicit index 'auto_identified_id_key' for table 'auto_identified'
CREATE
booktown=# -- Remove the table, and clean up the sequence behind it.
booktown=#
booktown=# DROP TABLE auto_identified;
DROP
booktown=# DROP SEQUENCE auto_identified_id_seq;
DROP
booktown=# -- Re-create the serial type's parts manually.
booktown=#
booktown=# CREATE SEQUENCE auto_identified_id_seq;
CREATE
booktown=# CREATE TABLE auto_identified
booktown-# (id integer UNIQUE DEFAULT nextval('auto_identified_id_seq'));
NOTICE: CREATE TABLE/UNIQUE will create implicit index 'auto_identified_id_key' for table 'auto_identified'
CREATE
|
Caution with Implicit Sequences |
|---|---|
|
Upon dropping a table, the implicit sequence created for the serial types are not automatically dropped. You must clean up after these types of sequences if you destroy a table which had a serial column, as shown in Example 3-26 , with the DROP SEQUENCE command. |
See Chapter 5 for more information on using sequences.
 
Continue to:
postgresql, psql, relational database, sql, standard, query, programming, administration
![]() |
|
|