1

What does this line mean?

KEY FK_CodigoCliente_idx (CodigoCliente),

CREATE TABLE tbvenda (
  Codigo int(11) NOT NULL AUTO_INCREMENT,
  CodigoCliente int(11) NOT NULL,
  DataVenda date NOT NULL,
  ValorTotal decimal(10,2) NOT NULL,
  Situacao int(11) NOT NULL,
  PRIMARY KEY (Codigo),
  KEY FK_CodigoCliente_idx (CodigoCliente),
  CONSTRAINT FK_CodigoCliente FOREIGN KEY (CodigoCliente) REFERENCES tbcliente (Codigo)
);
kkica
  • 4,034
  • 1
  • 20
  • 40
WSS
  • 153
  • 9

1 Answers1

4

KEY is a keyword in MySQL that essentially means "build an index on these columns". It is synonymous with INDEX (although more common, and a handy way to declare indexes directly in the CREATE TABLE statement.

This is actually explained pretty well in the documentation (although buried on the CREATE TABLE page):

KEY | INDEX

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thank you Gordon, but it's necessary I use it? – WSS Jun 06 '18 at 13:05
  • @WSS . . . Not at all. You wouldn't use it if you didn't want an index (for instance). You can always add indexes later (and that is often a good idea). It is generally redundant if the same column/columns are expressed as a `primary key` or `unique` constraint. – Gordon Linoff Jun 06 '18 at 13:07
  • In this case I have the primary key also.. so... – WSS Jun 06 '18 at 13:09
  • 1
    @WSS . . . The declaration of `PRIMARY KEY` already creates an index. There is no need to create an index on the same columns. (Well, actually, there might be some rare cases when you have a composite key and you want an index in a different order, but in general, one index on a set of columns is sufficient.) – Gordon Linoff Jun 06 '18 at 13:12