PRIMARY KEY definition in MySQL CREATE TABLE statement

Mysql

Mysql Problem Overview


What's the difference between this code:

CREATE TABLE samples (
  sampleid INT(11) NOT NULL AUTO_INCREMENT,
  sampledate DATE NOT NULL,
  location VARCHAR(25) NOT NULL,
  PRIMARY KEY (sampleid)
)
ENGINE=InnoDB;

and this:

CREATE TABLE samples (
  sampleid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  sampledate DATE NOT NULL,
  location VARCHAR(25) NOT NULL,
)
ENGINE=InnoDB;

code?

So a separate PRIMARY KEY statement or as part of a column definition. Same question for UNIQUE INDEX and UNIQUE keyword in column definition.

Mysql Solutions


Solution 1 - Mysql

The second syntax is merely a shortcut allowing you to specify the column and add an index on it in a single clause.

This works out fine in cases where you simply want to create a column and add an index on it.

You'll need to use the first syntax if you want to do something more complicated, such as adding an index based on multiple columns rather than a single column, or if you are adding or changing an index on an existing column; that is, you are not creating the column and the index on it at the same time.

Solution 2 - Mysql

MySQL allows uses the PRIMARY KEY directive to allow you to set the Primary Key dynamically. Supplying PRIMARY KEY as an argument to the constructor can only be called on creating the column. PRIMARY KEY(X), PRIMARY KEY(Y), PRIMARY KEY(Z) allows for changing the primary keys on subsequent queries.

Solution 3 - Mysql

The way I see it is.. The first method is used to create composite keys. While the second method (more readable to me) is primarily used if there is only primary key in the table.

The second method cannot be used if you want to implement composite key

Solution 4 - Mysql

There are many ways to skin a cat and above 2 examples are just 2 of them. They are identical. There's no difference.

Solution 5 - Mysql

They are literally the same. Here is a quick site that shows you the different ways (3) to do it. http://www.java2s.com/Code/SQL/Key/Defineanduseprimarykey.htm

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwaandersView Question on Stackoverflow
Solution 1 - MysqlthomasrutterView Answer on Stackoverflow
Solution 2 - MysqlhtmldrumView Answer on Stackoverflow
Solution 3 - Mysqluser4826347View Answer on Stackoverflow
Solution 4 - MysqlIcarusView Answer on Stackoverflow
Solution 5 - MysqlTIHanView Answer on Stackoverflow