EDITED: I recognize that some of you might wonder why I have 2 'id' values in my SQL code. I have addressed why in my particular case it seems to be needed in the comment below this question.
Given the following SQL code for creating table pokemon_users:
CREATE TABLE pokemon_users (
user_id BIGINT NOT NULL AUTO_INCREMENT,
pokemon_master_id BIGINT NOT NULL UNIQUE,
message varchar(255),
PRIMARY KEY (user_id)
)
QUESTION 1: would an index be created for column pokemon_master_id?
QUESTION 2: If so, what would be the difference between the index created for the PRIMARY KEY (user_id), and the pokemon_master_id index?
Question 1: Yes. A unique index.
Question 2: The primary key user_id is also a unique index. The difference is that you can only have one primary key but many unique indexes on a table.
Related
In mysql, say I have:
create table users(
id not null
)
Let's say I need to make id as a primary key. What is the difference between:
create table users(
id primary key not null
)
and
create table users(
id not null
primary key (id))
and
create table users(
id not null
constraint pk primary key (id))
I've been searching a lot for the meaning of constraints in this context, but I only find how to use them, not what it actually is.
A primary key is both not null and unique. So, this is very, very similar to a primary key:
create table users (
id int not null unique
)
The one additional feature of a primary key is that it is usually also the clustered index for the table.
A primary key declaration is a constraint. It has the following properties:
The columns are not null.
The columns are unique.
Only one primary key declaration is allowed per table (although multiple columns can be in the primary key).
In addition, the primary key columns often form a clustered index.
Except for the third condition, it is possible to declare these using multiple constraint declarations.
I have two tables as follow:
1st Table:
CREATE TABLE User (
User_ID VARCHAR(8)NOT NULL PRIMARY KEY,
User_Name VARCHAR (25) NOT NULL,
User_Gender CHAR (1) NOT NULL,
User_Position VARCHAR (10) NOT NULL,
);
2nd table:
CREATE TABLE Training (
Training_Code VARCHAR(8) NOT NULL Primary Key,
Training_Title VARCHAR(30) NOT NULL,
);
I am trying to create a table which has two foreign keys to join both of the previous tables:
CREATE TABLE Request (
User_ID VARCHAR(8) NOT NULL,
Training_Code VARCHAR(8) NOT NULL,
Request_Status INT(1) NOT NULL
);
When I am trying to set the foreign keys in the new table, the User_ID can be done successfully but the Training_Code cannot be set to foreign key due to the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
As I searched for this problem, the reason for it, is that data type is not the same, or name is not the same.. but in my situation both are correct so could you tell me what is wrong here ?
You need an index for this column in table Request too:
Issue first
CREATE INDEX idx_training_code ON Request (Training_Code);
Then you should be successful creating the foreign key constraint with
ALTER TABLE Request
ADD CONSTRAINT FOREIGN KEY idx_training_code (Training_Code)
REFERENCES Training(Training_Code);
It worked for me. But I've got to say that it worked without create index too, as the documentation of Using FOREIGN KEY Constraints states:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Emphasis by me. I don't know what's the issue in your case.
Demo
Explanation of the issue
The behavior mentioned in the question can be reproduced if the table Training is using the MyISAM storage engine. Then creating a foreign key referencing the table Training will produce the mentioned error.
If there's data in the table, then simple dropping of the table would not be the best solution. You can change the storage engine to InnoDB with
ALTER TABLE Training Engine=InnoDB;
Now you can successfully add the foreign key constraint.
I want to make composite key of 2 column id & code,the both columns altogether should act like Unique key for the table. while I have browsed and tried to create a table as follows,
Create table test (
`test_no` int not null AUTO_INCREMENT,
`code` varchar(5) NOT NULL,
`name` varchar(255),
`UPDBy` varchar(255),
PRIMARY KEY (`test_no`),
FOREIGN KEY (code) REFERENCES other_table(code)
// CONSTRAINT `K_test_1` Unique KEY (`test_no`,`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Just a second thought, can i make both the column as PK ? I think it will serve my purpose, RIght?
CONSTRAINT `K_test_1` Primary KEY (`test_no`,`code`) OR Primary KEY (`test_no`,`code`)
You seem to be on the wrong track somehow. Your table has an ID which is auto incremented. This is not supposed to be the primary key? Why do you call it ID then?
There are two ways to build a database: Either use the natural values a user is used to, such as an employee number a department number and so on. Or use IDs (which are usually hidden from the user). Than you would have an employee table with primary key "id" or "employee_id" or whatever, and the employee number just as a field. But as it must be unique, you would have an additional unique index on that field.
Having said that; you have a table "other_table" with primary key "code" it seems. So you are not using an ID concept here. Then why do you use it on table test? If this is a detail table on other_table, then I'd expect the composite key to be something like code + test_no (thus showing numbered tests per code) for isntance.
So the essence is: 1. Think about what your table contains. 2. Think about wether to use IDs or natural keys. The answer to these questions should help you find the correct key for your table. (And sometimes a table even doesn't have a primary key and needs none.)
You sure can make them both as PRIMARY KEY. If you don't want to, just use UNIQUE instead of UNIQUE KEY.
To set both as PRIMARY KEY, do as it follows:
...
PRIMARY KEY (`id`, `code`);
...
To set a UNIQUE CONSTRAINT, do as it follows:
...
CONSTRAINT `K_test_1` UNIQUE (`id`,`code`);
...
Hi I want to know if it is possible to make two primary keys in one table in MySQL. If so, please explain the concept behind this. I am asking because I have seen a table in which two primary keys are there with no auto increment set.
you can only have 1 primary key, but:
you can combine more than one column to be the primary key (maybe it's this what you have seen)
the primary key don't needs to be an auto-increment, it just has to be unique
you can add more than one index to one or more colums to speed up SELECT-statements (but slow down INSERT / UPDATE)
those indexes can be marked as unique, wich means they don't let you insert a second row with the same content in the index-fields (just like a primary key)
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
[...] A table can have only one PRIMARY KEY. [...]
No, but you can have other UNIQUE indexes on the table, in addition to the PRIMARY KEY. UNIQUE + NOT NULL is basically the same as a primary key.
What you have seen is probably a composite primary key (more than one column making up the unique key).
Use a Composite Primary Key...
e.g.
CREATE TABLE table1 (
first_id int unsigned not null,
second_id int unsigned not null auto_increment,
user_id int unsigned not null,
desc text not null,
PRIMARY KEY(first_id, second_id));
Also, check out the example here
You can use multiple columns for your primary key in this way:
CREATE TABLE
newTable
( field1 INT(11)
, field2 INT(11)
, field3 VARCHAR(5)
, field4 BLOB
, PRIMARY KEY (field2, field1, field3) <====
)
A table can have a single PRIMARY key, which may consist of one or more columns. A table can also have a number of additional keys defined on it, as UNIQUE KEY constraints.
It's not clear from your description whether you were looking at a table with multiple keys defined, or a table with a multi-column PRIMARY KEY.
What's the point of adding NOT NULL to a primary key field? Primary key is already not null + unique.
Here is an example:
CREATE TABLE student (
id int(11) AUTO_INCREMENT NOT NULL,
name varchar(255),
PRIMARY KEY(id)
)
Why not to define it like this instead:
CREATE TABLE student (
id int(11) AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY(id)
)
They are the same. Primary key got NOT NULL automatically.
You are asking, why do people bother adding the NOT NULL when it is unnecessary? Just because it is good style, I guess. And makes it explicit to the reader.
NULL is not equivalent to NULL(as NULL indicates an unknown or absent value), so you will be permitted to have multiple records that have NULL for the id, even though there's a primary key / unique constraint defined, hence the use of NOT NULL. That's if MySql even allows you to define a primary key on a nullable field.
In addition, as a primary key is often used in a foreign key in other tables, having one or more NULL values wouldn't make sense.
If PRIMARY KEY is declared without NOT NULL, NOT NULL is added to PRIMARY KEY implicitly so PRIMARY KEY with or without NOT NULL is the same.
The MySQL documentation says as shown below:
A unique index where all key columns must be defined as NOT NULL. If
they are not explicitly declared as NOT NULL, MySQL declares them so
implicitly (and silently). A table can have only one PRIMARY KEY. The
name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as
the name for any other kind of index.
And also, the MySQL documentation says as shown below:
The primary key for a table represents the column or set of columns
that you use in your most vital queries. It has an associated index,
for fast query performance. Query performance benefits from the NOT
NULL optimization, because it cannot include any NULL values. ...