JIYIK CN >

Current Location:Home > Learning > DATABASE > PostgreSQL >

Auto-increment values in PostgreSQL

Author:JIYIK Last Updated:2025/04/10 Views:

A VALUES in MySQL Auto_Incrementis an auto-incrementing variable that helps provide a unique identification for a set of data in a table. It is most commonly used PRIMARYin a key to uniquely index a row.

In MySQL, we can AUTO INCREMENTappend to any column we want.

CREATE TABLE test (
    id int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id)
);

However, today we will learn how to do this in PostgreSQL.

In PostgreSQL, SERIALthis is done using the keywordAUTO_INCREMENT

Let's make a table with a idand a column .colorCAT

create table cat(
	id SERIAL,
	color varchar not null
);

Let's go ahead and insert some values ​​into it.

insert into cat (color) values('black'), ('white'), ('brown'), ('tuxedo');

Make sure to specify COLUMN_NAMEso that the function doesn't select all columns and violate SERIALthe goal. If you dig into the PostgreSQL documentation, you'll learn that:

PostgreSQL documentation

When you click RUN, it will display the following result.

Output:

Using the SERIAL keyword

So, you can see that SERIALthe method is effectively implemented AUTO_INCREMENT.

A brief working guide to PostgreSQL SERIALand its alternatives

SERIALThe keyword generates an integer column. Instead SERIAL, you can also use SERIAL4, which represents 4 bytes.

If you want more identifiers or a larger range of automatically generated values, you can also use BIGSERIALor SERIAL8, which can hold up to 2^31identifiers.

SERIALmethod can be replaced with the following.

create sequence id_col_AI;
create table cat(
	id integer DEFAULT nextval('id_col_AI') NOT NULL,
	color varchar not null
);

So, what's going on here? SEQUENCEA new number generator is defined. If you want to START VALUEchange to a value you like, you can use START (your number)the parameter at the end of the declaration.

Then IDin the column, define it as to DEFAULTget the next value from the generator within the column. DEFAULTIt is preferred to assign NULLa default value other than to the column.

You then reference the created SEQUENCEand call NEXTVAL(your seq)to get the values ​​in sequence. This NOT NULLprevents the user from implicitly or explicitly inserting any NULL.

If your table is already created, you can also try extending it with ALTER TABLEthe method.

ALTER table cat ALTER id set DEFAULT nextval('id_col_AI');

Using the PostgreSQL AUTO_INCREMENTclauseGENERATED { BY DEFAULT || ALWAYS} AS

You can also add auto increment column using following code.

id integer generated by default as identity

We use BY DEFAULTinstead of ALWAYSbecause the former tends to write user values, but the latter only allows system-specified values. You can also use ALWAYS.

On many systems, this will probably work perfectly. However, if using ALWAYSreturns an error on insert, INSERTappend a INSERT INTO clause OVERRIDING SYSTEM VALUEto allow user-specific values.

insert into cat (color) overriding system value
values('black'), ('white'), ('brown'), ('tuxedo');

This uses an automatically appended sequence, such as the random generator mentioned earlier.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Terminate the PostgreSQL connection

Publish Date:2025/04/11 Views:199 Category:PostgreSQL

In this article, we will learn how to terminate a PostgreSQL session. Any open connections are run by background processes or tasks, PSQL which may no longer exist despite exiting the user interface or command line tool. Use ps -ef or grep

Single query to rename and change column type in PostgreSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

This article describes how to rename a column and change its type in PostgreSQL using only a single query. Renaming and changing column types in MySQL In MySQL , if you want to change the column type and rename it, you can use a simple stat

Joining columns using Select in PostgreSQL

Publish Date:2025/04/11 Views:176 Category:PostgreSQL

MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi

Using CASE in PostgreSQL

Publish Date:2025/04/11 Views:124 Category:PostgreSQL

This article shows how to use the statement in PostgreSQL CASE . CASE How to use the statement in PostgreSQL case Statements are similar to those in general-purpose programming languages if-else . But in SQL, if you want to write IF-ELSE ,

Using NOT IN with subqueries in PostgreSQL

Publish Date:2025/04/11 Views:93 Category:PostgreSQL

NOT IN The inverts the result of NOT simply using IN the operator. NOT IN The right side of the operator must have a subquery in which multiple columns are returned to check whether the expression matches the data. NOT IN Tends to return tr

Using variables in PostgreSQL

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article will demonstrate how we can declare and assign values ​​to variables in PostgreSQL. In PostgreSQL, DECLARE variables are declared using Often you will need variables in your PL/SQL scripts. In DECLARE the section called , y

Connect to PostgreSQL using a password

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article shows various ways to connect to PostgreSQL using a password. It can be through the command line, pgpass a file, PGPASSWORD an environment variable or a connection string. Connecting to PostgreSQL with a password using the comm

Deleting a database in PostgreSQL via PSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

There are two ways to access PostgreSQL objects and databases on your system. One is through an interface, such as a graphical interface like PGADMIN, and the other is the basic command line tool psql. Today, we will look at DROP DATABASE t

Using the database in PostgreSQL

Publish Date:2025/04/11 Views:132 Category:PostgreSQL

This article demonstrates connecting to a database, creating a new database, and creating a table in PostgreSQL. Available databases in PostgreSQL You can run the following command after opening the Postgres command line to view all availab

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial