MySQL and 2-columns Primary key - mysql

I'm beginning with MySQL, trying to set up a 2-columns primary key, I'm using phpmyadmin.
I managed to somehow mark two columns as a primary key (this is what i have right now, the primary columns are underligned) but they seem to act as two separate primary key, I can't add rows with the same ID and different region, or reversibly the same region and different ID.
What should i fix ? thanks !

If you run SHOW CREATE TABLE you will most likely see the following:
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
region VARCHAR,
....
PRIMARY KEY (id),
UNIQUE KEY somename (id,region)
So what has been created for you is a unique key. A unique key can be used as primary key, but you will have to get rid of your other primary key id.
This can be done by:
ALTER TABLE your_table_name DROP PRIMARY KEY;
Since I do not know all your specs, test the result and see if all the desired behavior is still in place.

Related

creating primary keys with constraints or not in mysql

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.

MySql: Composite Unique Key

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`);
...

Can a table have multiple Primary keys?

I am very confused right now, maybe you can help me to understand the problem better regarding the question that can a table have two primary keys if yes then how ? And if no, then why?
You ask if you can have more than one primary key field and you most certainly can. You can have only one primary key, but that can consist of as many columns as you need to uniquely identify your rows.
Use something like this when you are creating your table:
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
where P_Td and LastName are columns in your table.
If you think you want more than one primary key, then the answer is "not really." You can have only one primary key. However, you can have as many indexes as you want that have a unique constraint on them. A unique index does pretty much the same thing as a primary key.
for example :-
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,LastName)
)
Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).
No You cannot have two primary keys in one table, but you can have composite primary key
Because Primary key is an identity to the row and there can't be two IDs against a row.
A table can have many keys but by convention only one key per table is designated a "primary" one. Typically this may be the key deemed to be the "preferred" identifier for the information in that table or it may be a key singled out for some other specific purpose by the table's designer.
In principle whatever function or property you associate with the key designated "primary" could just as well be associated with any other key as well. Therefore for many practical purposes you could designate more than one such "primary" key if you so choose - but only if the limitations of any particular DBMS permit.
Under the relational model of data all keys are equal and there is no special function given to primary keys (in fact the relational usage of the term primary key originally referred to any and all keys of a relation and not just one key). Unfortunately many DBMSs don't respect this principle and may limit certain features to one and only one key of a table, making it necessary to be selective about which key gets designated as primary. So the answer to your question ought to be YES in principle. When you need to achieve it in some particular SQL DBMS the actual answer is: it depends.
You can only have 1 primary key - the range of keys that could all potentially be the primary key can be referred to as candidate keys. The one you select is the primary key, the other alternative keys can be implemented as unique constraints / indexes.
So whilst there is only 1 primary key, you can still ensure primality of other fields / combination of fields using the unique constraint / index.
No.The table have only on primary key. But that primary key can contain multiple field. Means when you create table and when you mention primary key, you can add more then one column which you want to.
for example
CREATE TABLE table_name ( col1 Datatype , col2 Datatype,col3 Datatype, col4 Datatype, PRIMARY KEY (col1,col2,col3) )
By this way you can add primary key in single table
On a table you can make indexes, which allow the internal database engine to process the contents of the affected columns (1 to many) for easy lookup. Because the engine is at that point already evaluating and sorting the contents of the fields, it can also easily ensure uniqueness of the values. Thus an index can span 1 to many rows, and optionally also be unique.
A primary key is a theoretically optional, though in practice mandatory, marker on a specific index that it's the eternally unique way of referencing a specific row in the table. It's usually either a GUID or an auto-increment integer (identity in SQL Server). The primary key itself is unique for any given table, and enforces a unique constraint by definition, but can optionally span multiple rows (a spanned index/key).
You could for example have a junction table containing only 2 fields, which are both foreign keys, and together form the primary key/index of the table.
You Can try FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
No.You cannot use more than 1 primary key in the table.for that you have composite key which is combination of multiple fields.
As you cannot define more than one column as Primary Key as below
create table test1 (col1 numeric(10) primary key, col2 numeric(10) primary key
,col3 numeric(10) primary key, col4 numeric(10))
It needs to be a composite key. Yes, we can have more than one column as primary key to solve some business requirements. Primary Keys ensures that the column(s) will not have duplicate values , Null in the table.
Below is the SQL to create a table with Composite Primary Key
CREATE TABLE track(
col1 numeric(10) , col2 numeric(10) ,col3 numeric(10) primary key, col4 numeric(10),
PRIMARY KEY (col1,col2,col3)
)
CREATE TABLE track(
col1 numeric(10) , col2 numeric(10) ,col3 numeric(10) , col4 numeric(10),
PRIMARY KEY (col1,col2,col3)
)

Rename Primary Key constraint on MySQL

I think this might be a bug with MySQL, but I'm not sure. Anyone can tell me how can I create a primary key for a table and then rename the primary constraint? If possible already create the primary key during table creation with the desired name.
All primary keys I create end up with the name "Primary". Already tried creating an index with the desired name before adding the PK, and renaming the PK using MySQL Workbench. None of them worked.
Anybody have any idea what's wrong and why can't I rename the PK name?
Thanks!
I'm not sure that MySQL allows to give names to primary keys in the first place. While there appears to be a syntax for it:
CREATE TABLE test (
test_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
CONSTRAINT my_test_pk PRIMARY KEY (test_id)
)
ENGINE=InnoDB;
... it doesn't show up in information_schema.TABLE_CONSTRAINTS or any other place I could spot so I have the impression that it's simply silently discarded.
The name you see is probably a hard-coded name your GUI client gives to all primary keys.
Edit: here's a quote from the manual:
The name of a PRIMARY KEY is always PRIMARY, which thus cannot be
used as the name for any other kind of index.

Is it possible to make two primary keys in one table?

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.