0

Objective: Have postgres generate ids automatically

CREATE TABLE user_privilege (
    id bigint NOT NULL,
    name character varying(255) NOT NULL,
    version integer
);
CREATE TABLE

INSERT INTO user_privilege (name, version) values ('XYZ', 1);

ERROR:  null value in column "id" violates not-null constraint

ALTER TABLE user_privilege ALTER COLUMN id SET DEFAULT nextval('user_privilege_id_seq'::regclass);

ERROR:  relation "user_privilege_id_seq" does not exist

Thanks!

EDIT:

I want to keep my id as bigint as all other tables have id as bigint.

1

2 Answers 2

3

You need to use either SERIAL or BIGSERIAL, not BIGINT.

CREATE TABLE user_privilege (
    id BIGSERIAL NOT NULL,

It's not clear whether your table has a PRIMARY KEY or UNIQUE constraint. But it should.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Appreciate it!
0

You have to create the sequence at first:

CREATE SEQUENCE user_privilege_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

and after you can use it:

ALTER TABLE ONLY user_privilege ALTER COLUMN id SET DEFAULT nextval('user_privilege_id_seq'::regclass);

Here is the create sequence documentation

7 Comments

SERIAL and BIGSERIAL data types automatically create a sequence. You don't have to create one manually.
Yes i know! but it seems that he want learn how to add sequence to a column manually.
The OP wants to generate ID numbers automatically. In PostgreSQL, the normal way to do that is to use the right data type, not to generate the sequence manually.
Yes, he wants to generate IDs automatically, and this can be acheved by using a sequence, and sequences can just be added explicitly or implicitly.
@riship89 You might also want to associate the sequence with the column: alter sequence user_privilege_id_seq owned by user_privilege.id. Then if the table or column is dropped the sequence is also automatically dropped and a truncate .. restart identity will reset the sequence.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.