The Wayback Machine - https://web.archive.org/web/20240927133940/https://www.geeksforgeeks.org/postgresql-create-auto-increment-column-using-serial/
Open In App

PostgreSQL – Create Auto-increment Column using SERIAL

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In PostgreSQL, sequences play a vital role when it comes to generating unique identifiers, especially for primary key columns. A sequence is a special database object that generates a sequence of integers, which can be used as unique IDs across rows in a table. In this article, we’ll look into how sequences work, the usage of the SERIAL pseudo-type, and explore examples to better understand how PostgreSQL handles sequences.

What is a Sequence in PostgreSQL?

A sequence is a database object designed to generate a series of unique integers. These are particularly useful for automatically populating a primary key column. When defining a primary key column, PostgreSQL offers a shortcut through the SERIAL pseudo-type, which simplifies sequence creation and management.

What is the SERIAL Pseudo-Type?

The SERIAL pseudo-type is a convenient way to create auto-incrementing primary keys. PostgreSQL offers three variants of the SERIAL type:

  • SMALLSERIAL: Uses 2 bytes and stores values from 1 to 32,767.
  • SERIAL: Uses 4 bytes and stores values from 1 to 2,147,483,647.
  • BIGSERIAL: Uses 8 bytes and stores values from 1 to 9,223,372,036,854,775,807.

When using the SERIAL type, PostgreSQL automatically handles sequence creation, setting the next integer as the default value for the column.

Syntax:

CREATE TABLE table_name(
    id SERIAL
);

In the above syntax by setting the SERIAL pseudo-type to the id column, PostgreSQL performs the following:

  • 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 above syntax is equivalent to the below statement:

CREATE SEQUENCE table_name_id_seq;
CREATE TABLE table_name (
    id integer NOT NULL DEFAULT nextval('table_name_id_seq')
);
ALTER SEQUENCE table_name_id_seq
OWNED BY table_name.id;

PostgreSQL provides three serial pseudo-types SMALLSERIAL, SERIAL, and BIGSERIAL with the following characteristics:

NameStorage SizeRange
SMALLSERIA2 bytes1 to 32, 767
SERIAL4 bytes1 to 2, 147, 483, 647
BIGSERIAL8 bytes1 to 9, 223, 372, 036, 854, 775, 807

Now let’s look into an example for better understanding.

Create Auto-increment Column using SERIAL Examples

Let us look at some of the examples to better understand the concept in PostgreSQL.

Example 1: Using the SERIAL Type

The following statement creates the ‘animals' table with the ‘id' column as the SERIAL column:

PostgreSQL
CREATE TABLE animals(
   id SERIAL PRIMARY KEY,
   name VARCHAR NOT NULL
);
INSERT INTO animals(name) 
VALUES('Dog');
INSERT INTO animals(name) 
VALUES('Cat');
SELECT * FROM animals;


Output:

Example 2: Returning the Generated ID

The following statement inserts a new row into the ‘animals' table and returns the value generated for the id column:

INSERT INTO animals(name) 
VALUES('Tiger')
RETURNING id; 

Output:

Best Practices When Using SERIAL in PostgreSQL

  • While sequences are unique, they should not be used as meaningful data. Gaps and resets can occur.
  • If your system requires unique IDs across multiple databases or instances, using UUIDs may be a better option than relying on SERIAL.
  • For extremely large datasets, the choice between SERIAL and BIGSERIAL can impact performance. Always benchmark according to your workload.


Similar Reads

How to Reset Auto Increment Counter in PostgreSQL?
PostgreSQL is a powerful, open-source, object-relational database management system (DBMS) developed by a community of contributors. In PostgreSQL, a counter is a type of variable that is used to keep track of a sequence of numbers. Counters used in databases to assign unique identifiers to new rows of data as they are inserted. In this article, we
4 min read
PostgreSQL - SERIAL
PostgreSQL has a special kind of database object generator called SERIAL. It is used to generate a sequence of integers which are often used as the Primary key of a table.  What is PostgreSQL Serial pseudo-type?In PostgreSQL, SERIAL is a pseudo-type used to create auto-incrementing integer columns. It simplifies the management of primary keys by au
3 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
How to Check Column Types in PostgreSQL?
In Procedural Language/Structured Query Language is an extension of SQL Language checking column types is an important aspect of understanding the structure and data stored in a database table. In this article, We will understand various method that helps in checking the column types in PostgreSQL with the help of examples and so on. Table of Conte
3 min read
How to Set a NOT NULL Column into NULL in PostgreSQL?
PostgreSQL is an open-source relational database management system in short RDBMS. It is commonly known for its reliability and vast feature set. We can clearly state that it is one of the most powerful RDBMS available. We often create some columns with NOT NULL constraints but later on, there will be some possibility that we have to add some NULL
4 min read
PostgreSQL - RENAME COLUMN
Renaming columns in PostgreSQL is a common task for database administrators and developers. The RENAME COLUMN clause, used with the ALTER TABLE statement, allows you to change the name of one or more columns in a table. Let us get a better understanding of the RENAME COLUMN Clause in PostgreSQL from this article. SyntaxALTER TABLE table_name RENAME
2 min read
PostgreSQL - Change Column Type
Changing the data type of a column in PostgreSQL is a common task that can be easily accomplished using the ALTER TABLE statement. Let us get a better understanding of Changing Column Type in PostgreSQL with the help of the ALTER TABLE statement from this article. SyntaxALTER TABLE table_name ALTER COLUMN column_name [SET DATA] TYPE new_data_type;P
3 min read
PostgreSQL - Identity Column
In PostgreSQL, the GENERATED AS IDENTITY constraint is used to automatically generate unique values for a column. It simplifies the management of auto-incrementing columns, similar to the SERIAL column but adhering to SQL standards. Let us get a better understanding of the GENERATED AS IDENTITY constraint in PostgreSQL from this article. Syntaxcolu
3 min read
PostgreSQL - ADD COLUMN
PostgreSQL offers the ADD COLUMN statement to add one or more columns to an existing database table. This is a crucial feature for modifying table structures to accommodate evolving data requirements. Let us understand how to use the ADD COLUMN Statement in PostgreSQL from this article. SyntaxALTER TABLE table_nameADD COLUMN new_column_name data_ty
2 min read
PostgreSQL - DROP COLUMN
In PostgreSQL, there are instances where you might need to remove unnecessary or obsolete columns from your database tables. The DROP COLUMN clause in the ALTER TABLE statement allows you to do this with ease. When you drop a column from a table, PostgreSQL automatically removes any associated indexes and constraints. In this article, we’ll learn h
2 min read
How to Add an Identity to an Existing Column in PostgreSQL?
PostgreSQL, a robust open-source relational database management system, offers a variety of tools for managing and organizing data. One such feature is the ability to add an identity to an existing column, which is particularly useful in situations when each row requires a unique identifier. In this article, we'll look at how to add identity to an
4 min read
PostgreSQL - Create table using Python
Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of creating tables in PostgreSQL using Python. Prere
3 min read
How to Create a New User With Full Privileges in PostgreSQL?
PostgreSQL provides a way to give a user full privileges to do anything with the database. The database objects like schema, table, function, and so on. The 'GRANT' command is used in PostgreSQL to provide a user with any specific privileges or to override the role of the user. In this article, we are going to learn how we can create a new user ass
6 min read
PostgreSQL - CREATE PROCEDURE
The CREATE PROCEDURE statement in PostgreSQL is used to create new stored procedures. Stored procedures are beneficial for encapsulating business logic, especially when you need to execute transactions. A drawback of user-defined functions is that they cannot execute transactions. In other words, inside a user-defined function, you cannot start a t
3 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE clause as the name suggests is used to create a new table. Creating tables is a fundamental aspect of database design in PostgreSQL. Let us get a better understanding of the CREATE TABLE Clause in PostgreSQL. SyntaxCREATE TABLE table_name ( column_name TYPE column_constraint, table_constraint table_constraint) INHERI
3 min read
PostgreSQL - CREATE SEQUENCE
A sequence in PostgreSQL is a user-defined schema-bound object that generates a sequence of integers based on specified parameters. The CREATE SEQUENCE statement is used to create sequences in PostgreSQL. Let us get a better understanding of the CREATE SEQUENCE Statement in PostgreSQL from this article. SyntaxCREATE SEQUENCE [ IF NOT EXISTS ] seque
4 min read
PostgreSQL - CREATE SCHEMA
PostgreSQL provides the CREATE SCHEMA statement to create a new schema in a database. Schemas in PostgreSQL help organize database objects such as tables, views, and functions, allowing for better data management and security. Let us get a better understanding of the syntax, options, and examples of using the CREATE SCHEMA statement in PostgreSQL.
3 min read
PostgreSQL - CREATE ROLE
PostgreSQL uses roles to represent user accounts. Unlike other database systems that use the concept of users, PostgreSQL treats roles as the primary means of access control. Roles that can log in are called login roles, which are equivalent to users in other systems. Roles that contain other roles are known as group roles. When you create a role,
4 min read
PostgreSQL - CREATE FUNCTION Statement
PostgreSQL allows developers to create user-defined functions to encapsulate reusable logic. The CREATE FUNCTION statement is used for this purpose, supporting various procedural languages, with plpgsql being one of the most commonly used. Let us look at the syntax, structure, and practical use of CREATE FUNCTION Statement in PostgreSQL, using the
3 min read
PostgreSQL - CREATE DOMAIN
PostgreSQL supports the creation of user-defined data types through the CREATE DOMAIN and CREATE TYPE statements. These capabilities allow for the customization and extension of data types to fit specific application needs, providing more flexibility and control over data integrity and consistency.  Let us get a better understanding of the CREATE D
3 min read
PostgreSQL - Create Database
PostgreSQL provides multiple ways to create a database, catering to different user preferences and requirements. This article will discuss various methods to create a database in PostgreSQL, including using the psql shell and pgAdmin. Creating a Database Using psql ShellTo create a database through the psql shell, you can use the CREATE DATABASE st
3 min read
PostgreSQL - Create updatable Views
Views in PostgreSQL provide a way to represent a subset of a real table, selecting certain columns or rows from an ordinary table. They are particularly useful for restricting access to the original table, allowing users to see only a specific portion of it. The table from which a view is created is known as the base table. PostgreSQL supports both
3 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks. Let us better understand the CREATE TABLE AS statement in Post
3 min read
PostgreSQL - CREATE TABLESPACE
In PostgreSQL, a tablespace is a mechanism used to map a logical name to a physical location on disk. Simply put, a tablespace is a disk location where PostgreSQL stores all its database objects, such as tables, indexes, and more. Understanding and utilizing tablespaces effectively can significantly enhance the management and performance of your Po
2 min read
PostgreSQL - CREATE TRIGGER
Triggers in PostgreSQL are powerful tools that allow you to automate actions in your database whenever certain events occur, like inserting, updating, or deleting data. From this article, we will better understand the CREATE TRIGGER Statement in PostgreSQL. Steps to Create Triggers in PostgreSQLTo create a new trigger in PostgreSQL, you follow thes
3 min read
PostgreSQL - CREATE INDEX
Indexes in PostgreSQL are crucial for improving the performance of database searches. They function similarly to a phone book. Imagine looking up Raju Kumar's phone number in an alphabetically ordered phone book. You quickly navigate to the 'K' section, find 'Kumar,' then 'Raju,' and finally get his phone number. This ordered search is efficient. H
3 min read
PostgreSQL - Create Tables in Python
Creating tables in PostgreSQL using Python is an essential skill for developers working with databases. This article will explore the process of creating new tables in the PostgreSQL database using Python. Why Create PostgreSQL Tables with Python?Using Python to create PostgreSQL tables is beneficial because Python offers powerful libraries like 'p
4 min read
PostgreSQL - Create Recursive Views
A view in PostgreSQL can be defined as a virtual table that is derived from underlying base tables or previously defined views. A view is nothing but a SQL statement that is stored in the database with an associated name. We have looked at what is the recursive query. To store the recursive query or to make a view out of a recursive query, PostgreS
4 min read