0

Question:

Is it possible to have enforce multiple column constraint when creating a table in mySQL, as opposed to later including it by altering the table?

Background:

I have noticed almost all answers to the question "how to create a multi column unique constraint in mySQL" involve using ALTER on a table, here are 2 examples from here alone:

The only examples I find which create multi column constraint when creating the table are for different flavors of sql:

Is there a way to create the constraint when creating the table as I find it is cleaner that way?

Community
  • 1
  • 1
puk
  • 16,318
  • 29
  • 119
  • 199
  • Is this a duplicate question, or has this question never been asked before by anyone? – puk Apr 22 '12 at 20:09

1 Answers1

1
CREATE TABLE mytable (
   field1 int,
   field2 int,
   field3 int,
   UNIQUE KEY (field1, field2, field3)
);
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • The only thing I can think of that CAN'T be done in a `create table` as opposed to an `alter` later on is creating two+ tables with mutually referential foreign keys. You'd have to alter the first created table after the fact, since you couldn't create the foreign key initially because the foreign table doesn't exist (yet). – Marc B Apr 22 '12 at 20:11