Home > Database > Mysql Tutorial > Why Doesn't AUTO_INCREMENT Work in PostgreSQL, and How Can I Achieve Auto-Incrementing IDs?

Why Doesn't AUTO_INCREMENT Work in PostgreSQL, and How Can I Achieve Auto-Incrementing IDs?

DDD
Release: 2025-01-22 11:37:10
Original
422 people have browsed it

Why Doesn't AUTO_INCREMENT Work in PostgreSQL, and How Can I Achieve Auto-Incrementing IDs?

Troubleshooting PostgreSQL's AUTO_INCREMENT

PostgreSQL doesn't support the AUTO_INCREMENT keyword used in other database systems like MySQL. Attempting to use it will result in a syntax error. This guide explains how to achieve auto-incrementing primary keys in PostgreSQL.

PostgreSQL 10 and Later: Using IDENTITY Columns

The recommended approach for PostgreSQL 10 and newer versions is to utilize the IDENTITY column. Unlike SERIAL columns, IDENTITY columns offer more flexibility with GENERATED BY DEFAULT and GENERATED ALWAYS options.

Creating a Table with an IDENTITY Column

CREATE TABLE staff (
  staff_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  staff    text NOT NULL
);
Copy after login

Adding an IDENTITY Column to an Existing Table

ALTER TABLE staff ADD COLUMN staff_id int GENERATED ALWAYS AS IDENTITY;
Copy after login

PostgreSQL 9.6 and Older: Utilizing SERIAL

For older PostgreSQL versions (9.6 and below), the SERIAL pseudo-type provides a similar auto-incrementing functionality.

CREATE TABLE staff (
  staff_id serial PRIMARY KEY,
  staff    text NOT NULL
);
Copy after login

SERIAL automatically creates and manages an associated sequence, ensuring unique, incrementing values for the staff_id column.

Controlling Inserted Values

For fine-grained control over inserted values, even overriding system defaults or user-provided values, use OVERRIDING {SYSTEM|USER} VALUE in your INSERT statements. This offers advanced control beyond simple auto-incrementing.

The above is the detailed content of Why Doesn't AUTO_INCREMENT Work in PostgreSQL, and How Can I Achieve Auto-Incrementing IDs?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template