How Do You Create a Primary Key in a PostgreSQL Table That Already Exists?

Problem scenario
You have a table that you would like to have a primary key.  You would like to add a new column to be the primary key.  How do you do this?

Solution
Here is a SQL command that is an illustration.  Assuming the table's name is "contint" and the new column you want to add is "continual_col" with a value type of integer, issue this command:

ALTER TABLE ADD COLUMN continual_col int PRIMARY KEY;

This is just an example.  Your primary key may have a different data type and a different name for the column.  Substitute "contint" and "continual_col" accordingly.  Then run the command.

Leave a comment

Your email address will not be published.