Data definition statement:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id)
)
What is the value and purpose of
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id)
?
as opposed to this
PRIMARY KEY (P_Id)
?
MySql docs do not really say much about this except for this.
The name of a PRIMARY KEY is always PRIMARY , which thus cannot be used as the name for any other kind of index. If you do not have a PRIMARY KEY and an application asks for the PRIMARY KEY in your tables, MySQL returns the first UNIQUE index that has no NULL columns as the PRIMARY KEY .
In MySQL, you don't need to use the word "constraint". So, the following should work in both Oracle and MySQL: create table penerbit( id_penerbit char(3) PRIMARY KEY, nama_penerbit varchar(100) NOT NULL );
When the table does not have a primary key, this statement is used to add the primary key to the column of an existing table. Following are the syntax of the ALTER TABLE statement to create a primary key in MySQL: ALTER TABLE table_name ADD PRIMARY KEY(column_list);
It's the same as MySQL ignores the CONSTRAINT pk_PersonID
part. You can check by creating the table and then dumping it or issuing SHOW CREATE TABLE Persons
.
I guess it supports this syntax only for compatibility with other SQL servers (but ignores it for primary and other local keys) and does not store its information (the constraint name).
However for usage with foreign keys the CONSTRAINT
keyword is used also in MySQL.
mysql> CREATE TABLE test.Persons (
-> P_Id int NOT NULL,
-> LastName varchar(255) NOT NULL,
-> FirstName varchar(255),
-> Address varchar(255),
-> City varchar(255),
-> CONSTRAINT pk_PersonID PRIMARY KEY (P_Id)
-> );
Query OK, 0 rows affected (0.50 sec)
server$ mysqldump -p test Persons
Enter password:
--
-- Table structure for table `Persons`
--
DROP TABLE IF EXISTS `Persons`;
CREATE TABLE `Persons` (
`P_Id` int(11) NOT NULL,
`LastName` varchar(255) NOT NULL,
`FirstName` varchar(255) DEFAULT NULL,
`Address` varchar(255) DEFAULT NULL,
`City` varchar(255) DEFAULT NULL,
PRIMARY KEY (`P_Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here is also test to prove MySQL doesn't store the constraint name anywhere and doesn't use it when printing errors (as mentioned for other SQL servers in question What is the purpose of constraint naming :
mysql> insert into Persons (P_Id) values(1);
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> insert into Persons (P_Id) values(1);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With