What is the difference between using a "Constraint" in "Foreign key" or not?

Asked

Viewed 2,215 times

5

When creating a table in Mysql I used to create fields CONSTRAINT FOREIGN KEY how are you following to create the foreign key:

CREATE TABLE socio 
(
  id_socio      INTEGER NOT NULL,
  nome          VARCHAR(256) NOT NULL,
  cpf           VARCHAR(11) NOT NULL,
  email         VARCHAR(256),
  id_situacao   INTEGER,
  CONSTRAINT pk_id_socio PRIMARY KEY (id_socio),
  CONSTRAINT un_socio_cpf UNIQUE (cpf),
  CONSTRAINT socio_id_situacao_fk_ref FOREIGN KEY (id_situacao) REFERENCES situacao (id_situacao)
);

What’s the difference when creating tables, use only the FOREIGN KEY or the FOREIGN KEY with CONSTRAINT to create foreign keys?

  • I believe the difference is that when you use CONSTRAINT <nome> FOREIGN KEY ... you are explicitly declaring to Constraint, that is, naming it. Already in the other situation, the database itself is in charge of appointing the Constraint. Take a look here.

  • So there is no correct difference? Only that in one case you give a name and in the other the back chooses

  • Exact! In terms of functionality there is no difference.

2 answers

5


The clause CONSTRAINT is used to name this integrity constraint. Just this, give a name of your choice.

Even without it it will still be a restriction imposed on the table, but the name will be the same as the index associated in FOREIGN KEY, and in case of not having an index specified it creates a name based on the column name. In this case as it does not have this index without the CONSTRAINT the name would be generated from the column. In your example the name of these restrictions will be pk_id_socio, un_socio_cpf, socio_id_situacao_fk_ref.

Documentation.

  • Basically, Constraint the user sets a name for FK, without the Constraint the system automatically generates a name for FK ?

  • Yeah, that’s just it.

0

Constraint ensures that data integrity, for example we have a table X and Y, where X has a FK with Y, if you try to delete a record from table X without deleting first from table Y the records that have the FK with the X the bank will not let, will give broken Constraint error

  • I know how the Constraint works, I want to know eh if there is difference between Constraint Foreign key and Foreign key

Browser other questions tagged

You are not signed in. Login or sign up in order to post.