Professional Documents
Culture Documents
increment Column
When creating a new table, the sequence can be created through the SERIAL pseudo-
type as follows:
First, create a sequence object and set the next value generated by the sequence
as the default value for the column.
Second, add a NOT NULL constraint to the id column because a sequence always
generates an integer, which is a non-null value.
Third, assign the owner of the sequence to the id column; as a result, the
sequence object is deleted when the id column or table is dropped
The following statement creates the fruits table with the id column as the SERIAL
column:
To assign the default value for a serial column when you insert row into the table, you
ignore the column name or use the DEFAULT keyword in the INSERT statement.
Or
1 INSERT INTO fruits(id,name)
2 VALUES(DEFAULT,'Apple');
PostgreSQL inserted two rows into the fruits table with the values for the id column
are 1 and 2.
To get the sequence name of a SERIAL column in a table, you use the
pg_get_serial_sequence() function as follows:
1 pg_get_serial_sequence('table_name','column_name')
You can pass a sequence name to the currval() function to get the recent value
generated by the sequence. For example, the following statement returns the recent
value generated by the fruits_id_seq object:
If you want to get the value generated by the sequence when you insert a new row into
the table, you use the RETURNING id clause in the INSERT statement.
The following statement inserts a new row into the fruits table and returns the value
generated for the id column.
The sequence generator operation is not transaction-safe. It means that if two concurrent
database connections attempt to get the next value from a sequence, each client will get
a different value. If one client rolls back the transaction, the sequence number of that
client will be unused, creating a gap in the sequence.
In this tutorial, you have learned how to use the PostgreSQL pseudo-type SERIAL to
create an auto-increment column for a table.
Related Tutorials