The difference is that the PRIMARY KEY constraint implies/enforces a NOT NULL CONSTRAINT. In the first example the varchar(255)
will be effectively promoted to varchar(255) NOT NULL
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE pk
( id varchar(255) PRIMARY KEY
);
CREATE TABLE uniq
( id int PRIMARY KEY
, accountid varchar(255) UNIQUE
);
INSERT INTO pk (id) VALUES(NULL);
INSERT INTO uniq (id, accountid) VALUES(1, NULL);
Result:
DROP SCHEMA
CREATE SCHEMA
SET
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pk_pkey" for table "pk"
CREATE TABLE
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "uniq_pkey" for table "uniq"
NOTICE: CREATE TABLE / UNIQUE will create implicit index "uniq_accountid_key" for table "uniq"
CREATE TABLE
ERROR: null value in column "id" violates not-null constraint
INSERT 0 1
The first insert fails because of the PK (-->>NOT NULL) constraint; the second one succeeds.