Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an automatically increasing primary key column in PostgreSQL

I am following the examples in CREATE TABLE:

CREATE TABLE distributors (
     did    integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
     name   varchar(40) NOT NULL CHECK (name <> '')
);

However, it gives me ERROR: syntax error at or near "GENERATED". Why is that and how should I fix it?

  • \! psql -V returns psql (PostgreSQL) 10.5 (Ubuntu 10.5-1.pgdg14.04+1)
  • SELECT version(); returns PostgreSQL 9.4.19 on x86_64-pc-linux-gnu (Ubuntu 9.4.19-1.pgdg14.04+1), compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4, 64-bit

Edits:

Thanks to @muistooshort, I checked the 9.4 docs. So I execute:

CREATE TABLE distributors (
     did    integer PRIMARY KEY DEFAULT nextval('serial'),
     name   varchar(40) NOT NULL CHECK (name <> '')
);

Nevertheless, it now gives me ERROR: relation "serial" does not exist...

like image 851
ytu Avatar asked Aug 15 '18 03:08

ytu


People also ask

Does Postgres automatically increment primary key?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .

Can a primary key be auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do I add auto increment to a column?

Here's the SQL statement to add AUTO INCREMENT constraint to id column. ALTER TABLE sales MODIFY id INT NOT NULL AUTO_INCREMENT PRIMARY KEY; Next we will add a couple of rows in sales table. As you can see, the MySQL has automatically increased and populated id column with values 7 and 8.


1 Answers

The SQL standard IDENTITY was added in PostgreSQL 10 but your server (which does all the real work) is 9.4. Before 10 you have to use serial or bigserial types:

CREATE TABLE distributors (
     did    serial not null primary key,
     name   varchar(40) NOT NULL CHECK (name <> '')
);

The serial type will create a sequence to supply values, attach the sequence to the table, and hook up a default value for did to get values from the sequence.

like image 141
mu is too short Avatar answered Sep 30 '22 10:09

mu is too short