PostgreSQL – Make an existing column as PRIMARY KEY

You can make an existing column of PostgreSQL Table as PRIMARY KEY using ALTER TABLE query and adding a constraint.

Make a Column as PRIMARY KEY

Consider the following table named students. No column in this table is marked PRIMARY KEY. Now, we will make the column id as PRIMARY KEY.

PostgreSQL DELETE query example

The SQL query to make column id of table students a PRIMARY KEY is:

</>
Copy
 ALTER TABLE students
	ADD CONSTRAINT students_pk PRIMARY KEY (id);
PostgreSQL - Make an existing column as PRIMARY KEY

When you describe the table with \d tablename command as shown below, there is a constraint added with id as PRIMARY KEY.

PostgreSQL - Make an existing column as PRIMARY KEY

Pre-requisites to make a column PRIMARY KEY

The first and foremost check that you to do before making a column as PRIMARY KEY is that: the values of the column should be unique.

Conclusion

In this PostgreSQL Tutorial, we have added a constraint on a column, to be PRIMARY KEY.