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...
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With