PostgreSQL Duplicate key value violates NOT NULL unique constraint

PostgreSQL duplicate key value violates unique constraint

Duplicate key value violates unique constraint in PL/pgSQL

Duplicate key

The cause of error: Duplicate key value violates unique constraint in PL/pgSQL.
The solution is to add unique values when you make insert or update on the table.

Create Students table

CREATE TABLE test.students
(
    id numeric NOT NULL,
    first_name character varying(50) NOT NULL,
    last_name character varying(50) NOT NULL,
    entry_date timestamp without time zone DEFAULT now(),
    address_id numeric,
    CONSTRAINT studentss_pkey PRIMARY KEY (id)
);

CREATE TABLE
Query returned successfully in 506 msec.

Wrong insert

INSERT INTO test.students 
(id, first_name, last_name) 
VALUES (1, 'David', 'Evans');
INSERT INTO test.students 
(id, first_name, last_name) 
VALUES (1, 'Jennifer', 'Turner');

ERROR: duplicate key value violates unique constraint “studentss_pkey”

DETAIL: Key (id)=(1) already exists.

Correct insert

INSERT INTO test.students 
(id, first_name, last_name) 
VALUES (1, 'David', 'Evans');
INSERT INTO test.students 
(id, first_name, last_name) 
VALUES (2, 'Jennifer', 'Turner');

INSERT 0 1

Query returned successfully in 396 msec.