2

I created a table named 'link' in PostgreSQL database. Then I created another table 'link_copy' with same structure as 'link'

CREATE TABLE link (
id select PRIMARY KEY,
url VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL);

CREATE TABLE link_copy (LIKE link);

I copied a row from 'link' to 'link_copy' that had 'id' = 2. After that I copied all rows from 'link' to 'link_copy'. I was surprised to see row with 'id' = 2 twice in 'link_copy'. If I had selected 'id' column to be primary key (which is UNIQUE NOT NULL by default), then why did it allowed the 'id' = 2 row to be inserted in 'link_copy' twice?

I am using postgresql 9.5 on Mac with pgadmin III.

screenshot for final link_copy status

3
  • CREATE TABLE link ( id select PRIMARY KEY, ... ); this not gives error ? Commented Sep 18, 2017 at 15:11
  • Show us tables creation code, exactly as you have it. Commented Sep 18, 2017 at 15:13
  • @OtoShavadze I have updated the code. All the code ran successfully on SQL Editor. I have also added the final screenshot. Commented Sep 18, 2017 at 15:59

2 Answers 2

4

When you use the CREATE TABLE command to create a new table with the same structure as another, it duplicates the columns, but not all of the constraints. Your link_copy table will not have a primary key defined after it is created this way.

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

1 Comment

Thanks! I checked the postgresql documentation for same: It states "Indexes, PRIMARY KEY, UNIQUE, and EXCLUDE constraints on the original table will be created on the new table only if INCLUDING INDEXES is specified."
1

Create table like below. This will create all constraints.

CREATE TABLE link_copy (LIKE link  including constraints including indexes);

Comments

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.