primary key specifying two columns - mysql

I am learning about sql and saw the following:
create table order_items
( orderid int unsigned not null,
isbn char(13) not null,
quantity tinyint unsigned,
primary key (orderid, isbn)
);
The line in question is: primary key (orderid, isbn)
How can you have two columns set as primary keys? How does this work? I understand having one column as a primary key like your social security, it's unique.

A primary key is one or more columns that have the following two properties:
The values are unique.
The columns are not null.
This simply means that pairs of values of those two columns uniquely identify a row. A table can only have one primary key.
In my opinion, I prefer auto-incremented numeric primary keys, with a secondary (unique composite) index for these two columns. One reason is foreign key references, which I find easier to maintain with a single column.

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)
)

DBLint Rule 31 means

DBLint is used to check database status. There are 46 rules. At www.dblint.org there are some simple explainations of each rule, but the Rule 31 which is described as below:
Defined Primary Key is not a Minimal Key:
A primary key is a minimal superkey. If the defined primary key is not a minimal superkey, it means that it is possible to identify a row with fewer attributes. Using a superkey instead of a primary key is even less attractive when other tables need to reference it. Each of the referencing tables will need to hold more information than actual needed, resulting in using more space and less efficient indices.
which is not quite clearify for me. If someone could explain this, Thank You!
A primary key is a super key if as subset of the columns in the primary key can also be used to uniquely identify a row.
Example:
Let's say you have a table containing all employees in a company. Each person gets an id but you also have a requirement that each person have a unique alias consistent of three letters for login name, email etc. This table could be:
create table employee
(
empID int not null auto_increment,
alias nvarchar(3) not null unique,
forname nvarchar(256) not null,
lastname nvarchar(256) not null,
constraint employee_pk primary key (empID, alias)
)
In this table the primary key is the combination of the empID and the persons three letter alias, but both the empID and the alias is required to be unique hence the primary key is a super key. It would be enough to only use a subset of the columns, e.g., the empID as a primary key to uniquely identify a single row, hence that will be a minimal super key.

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.