B
B
beduin012018-03-05 13:13:07
SQL
beduin01, 2018-03-05 13:13:07

What is the difference between constraint and foreign key?

I can set the integrity constraint both through constraint and through foreign key. Why is one better than the other?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
cicatrix, 2018-03-05
@beduin01

You are confusing sweet with soft.
Constraint constraint - when you set table parameters with create/alter table
you are saying that a constraint is being set for such and such a field.
Constraints can be primary key, foreign key, unique, default, check, etc. - these are all constraints.
Here is the table:

CREATE TABLE MYTABLE  (
   ID BIGINT NOT NULL CONSTRAINT PK_MYTABLE PRIMARY KEY,
   CLIENT BIGINT NOT NULL CONSTRAINT FK_MYTABLE_CLIENT FOREIGN KEY REFERENCES CLIENTS(ID),
   EMAIL NVARCHAR(100) NOT NULL CONSTRAINT UQ_MYTABLE_EMAIL UNIQUE,
   ACTIVE BIT NOT NULL CONSTRAINT DF_MYTABLE_ACTIVE DEFAULT (1)
)

Which translates as:
Create a table MYTABLE (with fields):
ID integer 64 bits, do not allow empty, constraint named PK_MYTABLE of the form "Primary key",
CLIENT integer 64 bits, do not allow empty, constraint named FK_MYTABLE_CLIENT of the form "Foreign key", which refers to the CLIENTS table, field ID,
EMAIL string of length 100, do not allow empty, constraint named UQ_MYTABLE_EMAIL of the form "Must be unique",
ACTIVE bit, do not allow empty, constraint named DF_MYTABLE_ACTIVE of the form "Default value" equal to 1
Yes and alternative syntax where the constraint keyword is not used.
It is mainly used when you need to explicitly set a name for a constraint.

K
Konstantin Tsvetkov, 2018-03-05
@tsklab

foreign key
Link to another table.
constraint
Limitation. May not be related to another table. For example, a date is limited to a certain period.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question