PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - Create Auto-increment Column using SERIAL

In PostgreSQL, the SERIAL keyword allows you to create columns that auto-increment. It's commonly used for primary key columns. When you define a column as SERIAL, PostgreSQL automatically takes care of creating a sequence object and setting up the default value for the column to fetch values from that sequence.

Here's how you can use SERIAL:

Creating a new table with an auto-increment column:

CREATE TABLE table_name (
    column_name SERIAL PRIMARY KEY,
    ... -- other columns
);

For instance, if you're creating a table to store users, it might look like this:

CREATE TABLE users (
    user_id SERIAL PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL
);

In this example, every time you insert a new user without specifying a value for user_id, PostgreSQL will automatically generate a new value.

How SERIAL works:

When you define a column as SERIAL, a few things happen behind the scenes:

  1. PostgreSQL creates a new sequence object with a name based on the column and table names. For our example above, it would be something like users_user_id_seq.
  2. The default value for the SERIAL column is set to fetch the next value from this sequence: nextval('users_user_id_seq'::regclass).

Using BIGSERIAL:

If you anticipate needing a larger range of numbers than provided by the SERIAL type (which is essentially an INTEGER), you can use BIGSERIAL, which is akin to a BIGINT in terms of storage and range.

CREATE TABLE large_data (
    id BIGSERIAL PRIMARY KEY,
    data TEXT
);

Note:

  • Remember, even though the SERIAL column will auto-increment, you can still explicitly set a value if needed, as long as it doesn't conflict with an existing value or a value the sequence might provide in the future.

  • If you're using PostgreSQL 10 or newer, you might consider using identity columns (GENERATED AS IDENTITY) as a more standardized way to achieve auto-increment behavior. They provide similar functionality but with additional capabilities and SQL standard compliance.

  1. Creating an auto-increment column in PostgreSQL using SERIAL:

    • Description: Creates a column that auto-increments with each inserted row.
    • Code:
      CREATE TABLE your_table (
          id SERIAL PRIMARY KEY,
          other_column VARCHAR(255)
      );
      
  2. Defining a primary key with auto-increment in PostgreSQL:

    • Description: Sets the auto-incremented column as the primary key.
    • Code:
      CREATE TABLE your_table (
          id SERIAL PRIMARY KEY,
          other_column VARCHAR(255)
      );
      
  3. Inserting data into a table with SERIAL column in PostgreSQL:

    • Description: Inserts data into a table with an auto-incremented SERIAL column.
    • Code:
      INSERT INTO your_table (other_column) VALUES ('some_value');
      
  4. Viewing the current value of a SERIAL column in PostgreSQL:

    • Description: Retrieves the current value of the auto-incremented SERIAL column.
    • Code:
      SELECT currval('your_table_id_seq');
      
  5. Resetting the SERIAL sequence in PostgreSQL:

    • Description: Resets the sequence to a specified value.
    • Code:
      SELECT setval('your_table_id_seq', 1);
      
  6. Adding SERIAL column to an existing table in PostgreSQL:

    • Description: Adds a new auto-incremented SERIAL column to an existing table.
    • Code:
      ALTER TABLE your_existing_table
      ADD COLUMN new_serial_column SERIAL PRIMARY KEY;
      
  7. Handling concurrency with SERIAL columns in PostgreSQL:

    • Description: SERIAL columns handle concurrency by using a sequence to ensure unique values.
    • Code:
      -- Automatically handled by the SERIAL column
      
  8. Customizing the start value and increment of a SERIAL column:

    • Description: Specifies a different starting value and increment for the SERIAL column.
    • Code:
      CREATE TABLE your_table (
          id SERIAL START WITH 100 INCREMENT BY 5 PRIMARY KEY,
          other_column VARCHAR(255)
      );