w3resource

PostgreSQL SERIAL: Auto-Incrementing Made Simple


PostgreSQL SERIAL Data Type

In PostgreSQL, the SERIAL data type is a convenient way to create auto-incrementing integer columns. It is commonly used for primary keys and ensures that each row receives a unique, sequential identifier. Under the hood, SERIAL is a combination of a SEQUENCE and a DEFAULT value.

This guide elaborates on the SERIAL data type, its syntax, examples, and best practices.


Syntax:

 
CREATE TABLE table_name (
    column_name SERIAL
);

Variants of SERIAL:

  • SERIAL: Integer (32-bit) auto-increment.
  • BIGSERIAL: Big integer (64-bit) auto-increment.
  • SMALLSERIAL: Small integer (16-bit) auto-increment.

Example 1: Creating a Table with SERIAL

Code:

-- Create a table with a SERIAL column
CREATE TABLE employees (
    emp_id SERIAL PRIMARY KEY, -- Auto-incrementing primary key
    name VARCHAR(100),         -- Employee name
    position VARCHAR(50)       -- Employee position
);

-- Insert rows into the employees table
INSERT INTO employees (name, position) 
VALUES ('Alice', 'Manager');

INSERT INTO employees (name, position) 
VALUES ('Bob', 'Developer');

-- Retrieve data from the employees table
SELECT * FROM employees;

Output:

emp_id	name	position
1	Alice	Manager
2	Bob	Developer

Explanation:

    1. SERIAL Definition:

    • The emp_id column is defined as SERIAL, so PostgreSQL automatically creates a SEQUENCE to generate unique, auto-incremented values.

    2. Inserting Rows:

    • No need to explicitly provide a value for emp_id; PostgreSQL populates it automatically.

    3. Generated Sequence:

    • The SERIAL column relies on a sequence object named <table_name>_<column_name>_seq.

Example 2: Using BIGSERIAL

Code:

-- Create a table with a BIGSERIAL column for large datasets
CREATE TABLE orders (
    order_id BIGSERIAL PRIMARY KEY, -- Big integer auto-incrementing key
    order_date DATE NOT NULL,       -- Order date
    total_amount NUMERIC(10, 2)     -- Total amount
);

-- Insert a row into the orders table
INSERT INTO orders (order_date, total_amount) 
VALUES ('2024-11-15', 150.00);

-- Retrieve data from the orders table
SELECT * FROM orders;

Output:

order_id	order_date	total_amount
1	2024-11-15	150.00

Example 3: Accessing the Sequence

Code:

-- Get the next value in the sequence
SELECT nextval('employees_emp_id_seq');

-- Set the sequence to a specific value
SELECT setval('employees_emp_id_seq', 100);

-- Check the current value of the sequence
SELECT currval('employees_emp_id_seq');

Explanation:

  • nextval: Retrieves the next sequence value.
  • setval: Manually sets the sequence value.
  • currval: Returns the current value of the sequence (only within the same session).

Best Practices

    1. Use SERIAL for Primary Keys:

    • Ideal for creating unique identifiers in small to medium datasets.

    2. Switch to BIGSERIAL for Large Datasets:

    • Use BIGSERIAL when you expect to exceed the range of 32-bit integers.

    3. Avoid Direct Manipulation of SERIAL Values:

    • Let PostgreSQL handle the auto-increment to ensure data consistency.

    4. Combine with Constraints:

    • Use SERIAL columns alongside PRIMARY KEY or UNIQUE constraints for robust table design.

Differences Between SERIAL and Identity Columns

In PostgreSQL versions 10 and later, GENERATED AS IDENTITY is an alternative to SERIAL:

Code:

-- Using GENERATED AS IDENTITY
CREATE TABLE products (
    product_id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    product_name VARCHAR(100)
);

Comparison:

Feature SERIAL GENERATED AS IDENTITY
Sequence Creation Creates implicitly Creates implicitly
Customizable Sequence Yes Limited
Standards Compliance No Yes (SQL Standard)

Advantages of SERIAL

    1. Ease of Use:

    • Automatically manages sequence creation and assignment.

    2. Default Behavior:

    • Automatically starts numbering from 1 and increments by 1.

    3. Compatibility:

    • Works seamlessly with other PostgreSQL features like foreign keys.

Potential Pitfalls

    1. Sequence Ownership:

    • Deleting the table doesn’t automatically drop the associated sequence.

    2. Limited by Integer Range:

    • SERIAL is limited to 2,147,483,647. Use BIGSERIAL for higher ranges.

    3. Not Standards-Compliant:

    • Consider GENERATED AS IDENTITY for future-proofing.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.