I'm learning mySQL, still on basic stuff.
My teacher has said that when writing, the best codes have first, all the tables; then, ALTER TABLE queries inserting keys to the tables. That way, we can properly name the keys. I know for sure he does that to foreign keys. He has taught this with primary keys examples as well; however, when providing files with answers for exercises he proposed, he typed the primary keys inside the tables, and later only altered the foreign keys.
How should I do it then? Always insert primary keys inside the tables, alter the foreign keys later? Or should I alter both primary and foreign keys? I'm currently trying to do he latter, and bumping into auto_increment issues for the primary keys.
Thank you for your insight!
You can't rename a primary key, so it makes no sense to do it later in an ALTER statement.
You're running into issues with auto_increment, because an auto_increment column also has to be (part of) the primary key. So you can not specify an auto_increment column but not make it primary key at the same time.
The thing is, this question is actually obsolete, as you can name your foreign keys also when creating the table. Which is for me the way that is prefered. Everything done in one statement. It would look like this:
CREATE TABLE foo (
id int auto_increment primary key,
bar int,
constraint my_fancy_fk_name foreign key (bar) references other_table(whatever_column)
);
I was creating a database and I want to make relation between tables "Member" and "Group_Member". But when I make the column "Memp_Id" as a foreign Key in table "Group_Member" as the picture shown this error appear.
I have checked the data type but both are the same. What I have to do now?
Reasons for error code 1215 cannot add foreign key constraint are listed in percona's article, but in the most cases the reasons are as follows:
child table's potential foreign key contains ids which is not present in parent table, but
your child table 'Group_Member' is empty so it is not applicable for
you.
The Local Key, Foreign Table or Column in the Constraint References
Have a Typo
The Column the Constraint Refers to Is Not of the Same Type or Width
as the Foreign Column, for e.g.if primary key has data type and width int(11) then foreign key's type and width also has to be as int(11)
Different Charsets/Collations Among the Two Table/Columns, for example if primary key has collation utf8_unicode_ci and foreign key has collation as latin1_general_ci then error will occur, so it should be the same.
The Parent Table Is Not Using InnoDB, for setting foreign key, if your parent table is of type MyISAM then it will show above error #1252 so it should be InnoDB.
The Parent Table Is Partitioned, you should check partition also.
Using SET DEFAULT for a Constraint Action, like Default NULL on PK or FK so Dont use Default on these keys.
Make sure they are both the same datatype and check if unsigned is the same on both, and that if you already have group_member rows then mem_id values will need to exist in the members table.
See here for more clarity of what unsigned means,
What does "unsigned" in MySQL mean and when to use it?
So I'm attempting to add a new foreign key to one of my tables as such:
ALTER TABLE `UserTransactions`.`ExpenseBackTransactions`
ADD CONSTRAINT `FK_EBTx_CustomAccountID`
FOREIGN KEY (`CustomAccountID` )
REFERENCES `UserTransactions`.`CustomAccounts` (`CustomAccountID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ADD INDEX `FK_EBTx_CustomAccountID` (`CustomAccountID` ASC) ;
and I keep getting the following error:
Error Code: 1005
Can't create table './UserTransactions/#sql-187a_29.frm' (errno: 150)
I've done quite a bit of changes in the past to this and other tables, and this is the first time I've run into this issue. Any ideas what is causing it?
UPDATE
My SHOW INNODB STATUS error:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110525 15:56:36 Error in foreign key constraint of table UserTransactions/#sql-187a_2c:
FOREIGN KEY (`CustomAccountID` )
REFERENCES `UserTransactions`.`CustomAccounts` (`CustomAccountID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `FK_EBTx_CustomAccountID` (`CustomAccountID` ASC):
Cannot resolve table name close to:
(`CustomAccountID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `FK_EBTx_CustomAccountID` (`CustomAccountID` ASC)
There's a nice checklist here.
Below is a running list of known causes that people have reported for the dreaded errno 150:
The two key fields type and/or size is not an exact match. For example, if one is INT(10) the key field needs to be INT(10) as well and not INT(11) or TINYINT. You may want to confirm the field size using SHOW CREATE TABLE because Query Browser will sometimes visually show just INTEGER for both INT(10) and INT(11). You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same. (More about signed vs unsigned here).
One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field. (thanks to Venkatesh and Erichero and Terminally Incoherent for this tip)
The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this. (Thanks to Niels for this tip)
One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won’t get an error message – it just won’t create the key.) In Query Browser, you can specify the table type.
You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL. You can fix this by either changing your cascade or setting the field to allow NULL values. (Thanks to Sammy and J Jammin)
Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns. (Thanks to FRR for this tip)
You have a default value (ie default=0) on your foreign key column (Thanks to Omar for the tip)
One of the fields in the relationship is part of a combination (composite) key and does not have its own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint. (Thanks to Alex for this tip)
You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship (Thanks to Christian & Mateo for the tip)
The name of your foreign key exceeds the max length of 64 chars. (Thanks to Nyleta for the tip)
In my experience, the errno: 150 usually indicates that the data types of the FOREIGN KEY column in the key table and relating table are not identical. Make sure that CustomAccounts.CustomAccountID and ExpenseBackTransactions.CustomAccountIDare the exact same type, including UNSIGNED if it applies.
If that doesn't help, please post the SHOW CREATE TABLE ExpenseBackTransactions; and SHOW CREATE TABLE CustomAccounts;
Catch 22. Foreign keys need indexes. MySQL doesn't order this query so that the index exists at the time it does it foreign key checks. Thus, first create the index, then add the foreign key in 2 separate queries.
I'm looking at the MySQL docs here and trying to sort out the distinction between FOREIGN KEYs and CONSTRAINTs. I thought an FK was a constraint, but the docs seem to talk about them like they're separate things.
The syntax for creating an FK is (in part)...
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
So the "CONSTRAINT" clause is optional. Why would you include it or not include it? If you leave it out does MySQL create a foreign key but not a constraint? Or is it more like a "CONSTRAINT" is nothing more than a name for you FK, so if you don't specify it you get an anonymous FK?
Any clarification would be greatly appreciated.
Thanks,
Ethan
Yes, a foreign key is a type of constraint. MySQL has uneven support for constraints:
PRIMARY KEY: yes as table constraint and column constraint.
FOREIGN KEY: yes as table constraint, but only with InnoDB and BDB storage engines; otherwise parsed but ignored.
CHECK: parsed but ignored in all storage engines.
UNIQUE: yes as table constraint and column constraint.
NOT NULL: yes as column constraint.
DEFERRABLE and other constraint attributes: no support.
The CONSTRAINT clause allows you to name the constraint explicitly, either to make metadata more readable or else to use the name when you want to drop the constraint. The SQL standard requires that the CONSTRAINT clause is optional. If you leave it out, the RDBMS creates a name automatically, and the name is up to the implementation.
In general (not necessary MySQL), foreign keys are constraints, but constraints are not always foreign keys. Think of primary key constraints, unique constraints etc.
Coming back to the specific question, you are correct, omitting CONSTRAINT [symbol] part will create a FK with an auto-generated name.
As of now, our CREATE TABLE DDLs are of this format - notice the UNIQUE KEY and FOREIGN KEY definition syntax we have used.
CREATE TABLE my_dbschema.my_table (
id INT unsigned auto_increment PRIMARY KEY,
account_nbr INT NOT NULL,
account_name VARCHAR(50) NOT NULL,
active_flg CHAR(1) NOT NULL DEFAULT 'Y',
vendor_nbr INT NOT NULL,
create_ts TIMESTAMP NOT NULL DEFAULT current_timestamp,
create_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',
last_upd_ts TIMESTAMP NOT NULL DEFAULT current_timestamp ON UPDATE current_timestamp,
last_upd_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',
UNIQUE KEY uk1_my_table(account_nbr, account_name),
FOREIGN KEY fk1_my_table(vendor_nbr) REFERENCES vendor(vendor_nbr)
);
In this format, MySQL is creating INDEX-es with the names uk1_my_table and fk1_my_table automatically; but the FK object name is something different - my_table_ibfk_1 (ie. tablename_ibfk_N – system defined) . So ALTER TABLE my_table DROP FOREIGN KEY fk1_my_table won’t work (and hence frustrating and raising alarms), as there’s no FK db object by that name.
Here’s an alternative DDL format wrt the constarints (Ref : https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html) :-
CREATE TABLE my_dbschema.my_table (
id INT unsigned auto_increment PRIMARY KEY,
account_nbr INT NOT NULL,
account_name VARCHAR(50) NOT NULL,
active_flg CHAR(1) NOT NULL DEFAULT 'Y',
vendor_nbr INT NOT NULL,
create_ts TIMESTAMP NOT NULL DEFAULT current_timestamp,
create_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',
last_upd_ts TIMESTAMP NOT NULL DEFAULT current_timestamp ON UPDATE current_timestamp,
last_upd_usr_id VARCHAR(10) NOT NULL DEFAULT 'DFLTUSR',
CONSTRAINT uk1_my_table UNIQUE KEY (account_nbr, account_name),
CONSTRAINT fk1_my_table FOREIGN KEY (vendor_nbr) REFERENCES vendor(vendor_nbr)
);
In this format, MySQL is still creating INDEX-es with the names uk1_my_table and fk1_my_table automatically, but the FK object name is not something different – it’s fk1_my_table as mentioned in the DDL. So ALTER TABLE my_table DROP FOREIGN KEY fk1_my_table works, but leaves behind the namesake INDEX.
And, note that ALTER TABLE my_table DROP INDEX fk1_my_table won’t work initially (when the FK is not yet dropped), with an error message that it is being used in a FK! If the DROP FK command has been executed successfully, only then the DROP INDEX works.
Hope this explains and helps resolve the confusion.
Can't answer for MySQL but FK's are constraints. Anything that forces your data into a certain condition is a constraint. There are several kinds of constraints, Unique, Primary Key, Check and Foreign Keys are all constraints. Maybe MySQL has others.
Sometimes words are allowed in commands but not required sheerly for readability like the FROM in the DELETE statement.
If I'm not wrong, the constraints need indexes, so when you create, for example, a foreign key constraint MySQL automatically creates an index too.
I am going to throw my hat in the ring here, although I don't actually know if my answer is accurate, so if you know the internal guts of database engineering, please correct me. But if I am right, I think this will help.
A Foreign Key and its associated Foreign Key Constraint are not the same thing, in the way a car engine and a crank-shaft are not the same thing. The engine converts gasoline explosions into straight line motion (the pistons), and the crankshaft converts that straight-line motion into turning motion, which then turns the wheels of the car. Together, the engine and the crank-shaft make the car go.
Likewise, a Foreign Key and a Foreign Key Constraint are not the same thing, but they work together to create the idea of a "Foreign Key Relationship".
DEFINITIONS:
"Foreign Key" is short for Foreign Key Index.
"Constraint" is short for Foreign Key Constraint.
The Index and the Constraint together make the "Foreign Key Relationship".
The Foreign Key Relationship is the requirement for a value in a child table to exist in its parent table, thus ensuring data integrity in a database.
Because Key means Index, we don't say "Foreign Key Index". We just say Foreign Key, but not saying "Index" is the cause of much confusion.
Creating a Foreign Key (a Foreign Key Index) creates a Binary Search Tree (also called a dictionary, because the tree is used to look up values). The Binary Search Tree (BST) then exists in computer memory and takes up physical disk space, but allows for O(log n) JOIN access time (almost instantly) from the child table to the parent table.
Creating a Foreign Key Constraint is creating a rule, which is a piece of code that gets called when you process (INSERT, SELECT, etc...) on the foreign key column. A constraint is essentially a database trigger. A constraint is like an email filter: a piece of code that gets called on a certain action, such as WHEN (new email) IF (From: crzy#xgfrnd.com) {SEND TO Trash Folder;}.
Thus, a Foreign Key "Constraint" would be a piece of code that gets called (a trigger, essentially), that looks like such: WHEN INSERT child_column IF (NOT IN parent_table) DO NOT ALLOW INSERT.
And then you have your Cascades and Updates and Delete rules (constraints), wth their various if / then conditions and operations, etc...
So, a "Foreign Key" is a BST dictionary mapping child table column values to parent table column values. The purpose of the Foreign Key is speed (NOT data integrity, since data integrity can be achieved, albeit slowly, without an index).
A Foreign Key Constraint is a rule: code that gets triggered on SQL statements, and that rule uses the BST as a dictionary for fast processing, to avoid traversing tables, which may eventually create Cartesian-like behavior. The purpose of the Foreign Key Constraint is data integrity.
I have never created a parent table where the referenced parent column was not itself a key in the parent table. So the question then is, is the Foreign Key Index (the BST dictionary) actually needed? The Constraint is definitely needed, to ensure data integrity, but Foreign Key Index (the BST dictionary) is actually not needed to fulfill the Foreign Key rule, thus, "Key" and "Index" have two different definitions. The "Index" is the BST tree, and the "Key" is the rule (the idea that the child value must exist in the parent table). In MySQL, however, the Foreign Key Index is needed, only because they programmed it that way, but they didn't have to. Having a BST tree is just faster, when the parent column is not itself indexed. I would never recommend making the referenced parent column not a key (index). But if someone did reference a non-indexed parent column using a Foreign Key Constraint without a BST, then the SQL operations would be progressively slow, and your application may eventually come to a crawl.
THE CONFUSION: Adjectives and verbs.
When we say "Foreign Key" colloquially, we are usually referring to the Foreign Key Relationship, not the Foreign Key Index. But the word Key means Index. So that's the root source of all the confusion. I.e. lack of reserved keyword definition standards. In a MySQL CREATE TABLE statement, FOREIGN KEY means the Index (the BST), and CONSTRAINT names the rule, therefore, the confusion is coming from the difference in the phrase "Foreign Key" when we speak, versus "Foreign Key" being defined in an actual SQL statement.
In computer code, "Foreign" is an adjective and "Key" is a noun, meaning the Index.
In colloquial speech, the phrase "Foreign Key" is an adjective, and the words "Index", "Constraint", and "relationship" are all nouns. When we speak to each other across office cubicles, "Foreign Key" means the "idea" of data integrity (i.e. the rule, not the index).
Unfortunately, programmers are always searching for short-hand ways of typing, which often causes confusion. Everything in computer science is a trade-off, and that includes coding style.
If the syntax for creating a MySQL table instead used the following reserved words, then the confusion would disappear: FOREIGN KEY CONSTRAINT fk1_rule_child_column FOREIGN KEY INDEX (fk_bst_child_to_parent_column) REFERENCES parent_table (parent_column)
Furthermore, since MySQL always creates both an Index and a Constraint, the MySQL creators could have completely hidden (abstraction) the dual element of the Foreign Key Relationship. Or, perhaps I should say, they could have bundled them together so the user doesn't have to think about the dual aspect, and instead just creates a "Foreign Key" my_foreign_key with the dual details hidden.
Nevertheless, MySQL is inexpensive, robust, and it's great. For the record, I have zero complaints, and I have only gratitude for the creators. For my part, they can do as they please.
Incidentally, as a style recommendation, you should ALWAYS name your parent and child columns the same, and your table names should ALWAYS contain their Foreign Key Relationships. So your tables
customers
products
attributes
orders
should instead be named
customers
products
product_attributes
customer_product_orders
That way, you and your successors know the foreign key relationships just by reading any table name. If that's too much typing for you, then
cust
prod
prod_attr
cust_prod_ord
That being said, I am guessing. I don't actually know if my BST and Rule explanation is correct, but I think it's correct, and hopefully will clear up this confusing issue. But I would appreciate if you database-guts guys out there would either confirm, modify, supplement, or deny what I have written, and if I am mistaken, what is the real answer, so we can finally get this multi-generational mystery solved. If I am completely off, and this answer needs to be deleted, that is fine too.
This is probably the most confusing topìc in MySQL.
Many people say that, for instance, the 'PRIMARY KEY', the 'FOREIGN KEY', and the 'UNIQUE' key are actually indexes! (MySQL official documentation is included here)
Many others, on the other hand, say that they're rather constraints (which does make sense, cause when you use them, you're really imposing restrictions on the affected columns).
If they really are indexes, then what's the point in using the constraint clausule in order to give it a name, since you're supposed to be able to use the name of that index when you created it?
Example:
... FOREIGN KEY index_name (col_name1, col_name2, ...)
If FOREIGN KEY is an index, then we should be able to use the index_name to handle it. However, we can't.
But if they're not indexes but actual contraints which do use indexes to work, then this does make sense.
In any case, we don't know. Actually, nobody seems to know.