countryroadscat
countryroadscat

Reputation: 1750

PRIMARY KEY vs. CONSTRAINT pk_id PRIMARY KEY (id)

In postgres(and many others) we can declare primary key in two different ways:

Method 1:

create table MyTable(
    MyId SERIAL PRIMARY KEY
)

Method 2:

create table MyTable(
    MyId SERIAL,
    CONSTRAINT pk_myid PRIMARY KEY (MyId)
)

My question is: Is there any difference between these declarations (except syntax)? Maybe Hibernate mapping? Or maybe one of these is called a good practice to use?

What I already know - second one is used to set a PRIMARY KEY on multiple columns.

Upvotes: 3

Views: 1904

Answers (1)

user330315
user330315

Reputation:

The only difference between the two versions is the name for the PK constraint. In the first case Postgres (or the the DBMS in question) will generate a name for you. Postgres will create the name mytable_pkey. Oracle would choose a name like SYS_C0029159

In the second version, you have the control over the name.

But there is no difference in terms of functionality.

I prefer the second version so that I can control which name is used for the constraint.

Upvotes: 6

Related Questions