Skip to content
Advertisement

How to add a column default?

I created a Postgres DB which contains 5 tables. Then I realized that the column student.student_id lacks a column default to generate an UUID:

CREATE TABLE student (
     student_id UUID PRIMARY KEY,
     first_name VARCHAR(100) NOT NULL,
     last_name varchar(100) NOT NULL,
     date_of_birth Date NOT NULL
)

Knowing that some tables are linked to the student table, how can I add to the function as column default for student_id so that the result will be:

     student_id UUID PRIMARY KEY DEFAULT uuid_generate_v4()

Advertisement

Answer

Use ALTER TABLE:

ALTER TABLE student
ALTER COLUMN student_id SET DEFAULT uuid_generate_v4();

Column defaults do not conflict with FOREIGN KEY references.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement