Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using or not using CONSTRAINT keyword on SQL Server

What is the difference between using or not using the CONSTRAINT keyword when working with Foreign Keys on SQL Server?

I noticed that apparently both worked the same in this specific case, without CONSTRAINT:

CREATE TABLE ClientsPhones
(
     ClientPhone varchar(10) NOT NULL,
     ClientID smallint NOT NULL,

     PRIMARY KEY (ClientPhone),
     FOREIGN KEY (ClientID) REFERENCES Clients(ClientID)
);

And with CONSTRAINT:

CREATE TABLE ClientsPhones
(
    ClientPhone varchar(10) NOT NULL,
    ClientID smallint NOT NULL,

    PRIMARY KEY (ClientPhone),
    CONSTRAINT fk_ClientID 
      FOREIGN KEY (ClientID) REFERENCES Clients(ClientID)
);

Both didn't let me add records to the table unless the ClientID already existed on the Clients table, and the same ClientID and ClientPhone weren't already on the ClientsPhones table.

Is there any real difference between the two besides the fact that I'm able to name the constraint?

like image 895
user1676874 Avatar asked Feb 28 '15 22:02

user1676874


2 Answers

If you don't create constraint.it will automatically create own constraint name

the foreign key index name is generated using the name of the referencing foreign key column Automatically.

So there is no way to see difference of using and not using Constraint keyword. by default constraint name will be defined.

like image 86
Hell Boy Avatar answered Sep 30 '22 17:09

Hell Boy


I did some research and don't believe Hell Boy's answer was as clear as it could be and had some misinformation.

Every constraint you add to a database has a name set by default. This includes PRIMARY KEY, FOREIGN KEY, DEFAULT, NOT NULL. It isn't necessarily the name of the column(s) used.

You can imagine that when you don't use the CONSTRAINT keyword SQL Server puts it there as well as generates a name for you.

If you want to remove or change a constrain you would either have to delete the entire table and recreate it with the correct constraints or you can reference the constraint by name and then alter it somewhat like a column using the ALTER keyword. This can be useful for when you need to delete a table with a foreign key. If you name the foreign key constraint you can delete it and then the table instead of having to delete the table the foreign key points to.

like image 39
Deeswoc Avatar answered Sep 30 '22 16:09

Deeswoc