set two fields as primary key - mysql

I show following sql query.
ALTER TABLE dbo.YourTableNameHere
ADD CONSTRAINT PK_YourTableNameHere
PRIMARY KEY(Item_Id, Purchase_Id)
What does it mean by "PK_YourTableNameHere". Is it current primary key of the table?

The name of the primary key constraint is optional (see doc).
Call it what you like or omit it altogether - it makes no difference.

It is a name that you assign to the PRIMARY KEY you are adding to the table. In your example there is no current PRIMARY KEY (or, if there is, your command will fail).
The name can be any valid identifier you want. The purpose of given the constraint a name is to make it easier to manipulate (primarily, to drop it) later.

Related

When creating a SQL table, why or why not use the CONSTRAINT keyword?

For example in the last line of the following create table statement, instead of writing CONSTRAINT PK_food PRIMARY KEY (food_numb), couldn't I have just done PRIMARY KEY(food_numb)?? What is the purpose of the CONSTRAINT keyword?
CREATE TABLE food
(
food_numb integer,
food_description varchar (256)
source_numb integer,
amount integer,
CONSTRAINT PK_food PRIMARY KEY (food_numb)
)
We normally use constraint for primary key when we take a composite primary key
eg:
CONSTRAINT PK_Food PRIMARY KEY (food_num,food_description)
In this case you have two options. There are many other types of constraints which you really do have to use CONSTRAINT keyword.
Refer this for more mysql constraints
You must specify CONSTRAINT name if you want to refer to it further. For example, for its deletion.
You may skip CONSTRAINT keyword (and, of course, its name) and allow MySQL to generate the name automatically always, but do this only if you have no plans to refer to the constraint name in future.
You can always look for the constraint name (both specified explicitly and generated automatically) using SHOW CREATE TABLE statement.
It is not reasonable to use CONSTRAINT clause for PRIMARY KEY - this is an exclusion, the name specified will be ignored, and predefined name PRIMARY will be used anycase. This is documented.

Can we make existing column as primary key?

I have one column name Token and I'm generating random numbers and saving them in token but sometimes it saves duplicate tokens so I want to make it unique.
I want to know will it affect existing records.
If you try to add a unique constraint (or primary key constraint) to a column that contains non-unique values, the alter statement will just fail. You need to first update the column so all values are unique (or remove duplicates), and then alter the table.
ALTER table Student add primary key (studentID)
Use the Alter command to edit table's DDL and then add a primary key to it by specifying the column.
If the primary key already exist, then first you will have to drop it before defining another PK by -
ALTER table STUDENT drop CONSTRAINT <constraint_name>
Try doing this
ALTER table_namePersons ADD UNIQUE (Token);
After doing this if you'll try to insert a duplicate key you will have an error and catching it you can generate another token

Foreign Key Constraint syntax

I'm new to learning SQL syntax and came across this example in a book. I understand the need for foreign keys and using the constraint function in order to set the key to another table that is created (EMPLOYEE_TBL in this example).
My question is why it listed the line CONSTRAINT EMP_ID_FK FOREIGN KEY (EMP_ID). What exactly is the EMP_ID_FK portion? Since you just need to use the CONSTRAINT function to set a field on you child table to the parent table, couldn't you just write it as CONSTRAINT FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID)); instead?
Am I understanding this incorrectly? Any help would be appreciated. Thanks!
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID CHAR(9) NOT NULL,
DATE_HIRE DATE NULL,
DATE_LAST_RAISE DATE NULL,
CONSTRAINT EMP_ID_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID));
The clause CONSTRAINT EMP_ID_FK simply gives a name to the constraint. This becomes necessary later if you want to disable or drop the constraint. You are correct that the name (EMP_ID_FK) is optional; if you omit it you can also omit the CONSTRAINT keyword, as the clause FOREIGN KEY is enough to tell the interpreter what it is you want.
Naming your constraints is entirely optional but is considered good practice for documentary purposes and in case, as I said, you later need to do something with the constraint. If you omit the name, the database will automagically name the constraint for you, but good luck finding out what that name is.
Put it like this.
Table 1 has to have a reference to Table 2. Table 2 has a Primary Key ID that is a unique value, that means it can be accessed with this ID, as it is unique in all the rows of this table. Now table Table 1 needs to reference to that ID. You need to store that ID in Table 1 so you can reference to it and you know to which Table 2, Table 1 points. You use the naming convention Table2_ID_FK to know that that Field in Table 1 is a reference to the ID of table 2. The constraint is to set the actual relation between these tables.

Add another primary key to table in mysql

I want to add another primary key to a table in mysql.
I use phpmyadmin to communicate with mysql server.
When I click the primary icon for the desired field it gives me this error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Edited:
here's the query:
ALTER TABLE `files` DROP PRIMARY KEY ,ADD PRIMARY KEY ( `file_type` )
How can I do it?
As the name "primary" key says, there may be only one of that (ref: Highlander).
What you might want to try is a UNIQUE KEY, that acts just like a primary for most purpouses. Auto_increment doesn't seem to fulfill any purpouse if used a second time - what'ts the point of two fields carrying exactly the same information?
I believe in your case, what you need is a composite key. I do not know your table structure, but here is a general example taken from here,
CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)
In this case, there is a combination of 3 columns which avoid the duplicate records as you require. Please let me know if I have any mistakes in understanding your scenario.
The error message says it, I think:
the auto_increment column must be key.
So use this query first:
ALTER TABLE 'files' CHANGE 'id' 'id' INT( 10 ) UNSIGNED NOT NULL;
this will remove the auto_increment.
Also, I recommend the Uniqe key as suggested by other answer. I believe there should always (almost) be an Id column in each table.
We can Give Primary Key only once for a table. You can prefer UNIQUE KEY to prevent duplicate records
ALTER TABLE Persons
ADD UNIQUE (P_Id)
You can mark all the fields you want as primary keys, including the existing one. The system internally will drop the existing one and will set all you marked.

Foreign Key add fails in MySQL with Error Code 1005, number 150

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.