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.
Related
After googling a lot, I found 2 statements for Primary Key.
Some says, Primary key can be only one in a table.
Some says, Primary key can consists of more than one column.
And also says, it is the difference between Primary key and Unique key.
I read this post: difference between primary key and unique key
But, this post also confuses this difference.
My Question is:
When Primary key can consists of multiple columns, then how can it be only
1 for a table and then how this can differ from Unique Key except from
null value difference?
A primary key is used by the optimiser to create a clustered index around that key. If that key happens to be a combination of columns (for instance in a table that handles a many to many relationship) then that is fine. A unique key is an attribute of something that is unique to that thing but not an attribute that you want to use as the primary key.
One example that i work with is cars. The vin is unique to the car. However because the vin and body number are used at different stages in the vehicles life. Whilst it is unique to the car, it isn't a good primary key candidate. So we have a unique identifier per car as a primary key.
Similarly we handle user group tables with primary keys over multiple columns. So the combination of the userid and the usergroupid is a primary key preventing the entry of people in to the same group more than once. The use of a primary key here rather than a unique key is to conform to the 3rd normal form mostly.
I hope that helps but if you would like further clarification please let me know.
You can have only one primary key in a table, but it can consist of multiple columns. This doesn't mean that each column is a primary key, but that the combination of all these columns' values are unique.
A unique constraint is similar to a primary in preventing duplicate values, but a unique constraint allows nulls (since they aren't values). A primary key does not. You could think of a primary key as a unique not null constraint.
In SQL: Any number of sets of one or more columns can be declared UNIQUE. One set of columns can be declared PK (PRIMARY KEY). PK means UNIQUE NOT NULL. A set of one column is "simple" & a set of more than one is "composite".
In standard SQL a UNIQUE column set has a distinct subrow value in every row--where NULL<>NULL. MySQL does that--but some DBMSs evaluate that "distinct" treating NULL equal to NULL. Read the manuals.
SQL DBMSs use UNIQUE & PK declarations for other things--typically for default INDEXes. INDEX is not standard SQL & is a different notion. Read the manuals.
PK & other terms have different definitions in the RM (relational model)--even for tables that have an obvious interpretation as relations because they have no duplicate rows & no NULLs. Read some published academic textbook(s).
There's no need for PK in SQL or the RM--it's just a tradition.
Re related terms in SQL & the RM.
Primary keys can consist of any number of columns. They then have three properties:
The combination of values in the columns is unique.
The values in each column are never NULL.
There is only one primary key per table.
The first two conditions can be true on any number of columns or combinations of columns in a table. These are called candidate primary keys. You would implement them with unique and not null constraints.
The third condition is simply states that at most one of these candidates can be chosen as the primary key.
One way to think about this is that the primary key is special. For example, in MySQL, the data is actually ordered on the data pages by primary key (this is called a clustered index). However, nothing in SQL in general requires that the primary key also be a clustered index, and not all databases implement this.
There is no inconsistency in what you read
A primary key is "one or more columns, whose combination of values must appear on only one row"
A primary key can be single column, and then the value must be unique. It can be multiple columns, and all values considers together must be unique:
Key1, Key2
1 , A
1 , B
2 , A
2 , B
Here it's true that both key1 column and key2 column have repeated values but when we consider the combinations of key 1 and key 2, they are unique: 1A, 1B, 2A, 2B
Regarding the PK vs Unique Key query, see this answer. It goes into more detail about primary keys, the basic principle of which is that none of the columns making up the primary key allows a null value: What's wrong with nullable columns in composite primary keys?
the main differences between a primary key and a unique key is the primary key main job is to uniquely identify a row in a table and the main job for a unique key is to allow you to place additional unique conditions on your columns
For example say you have a employees table with employee ID as the primary key and a accountNumber.. the accountNumber would be set as the unique ID... so you wouldn’t have the accountNumber set as the primary key incase accountNumber is generated by another organisation outside of your database..
When Primary key can consists of multiple columns, then how can it be
only 1 for a table and then how this can differ from Unique Key
except from null value difference?
Its true that a table can only have one primary key. This key can contains multiple columns(combination of columns). That combination of columns is collective is a Primary Key.
Lets take an example
Table A
Id, Clientid, Branchid, Name, Address, .......
Here I created a primary key with combination of "Id, Clientid, Branchid"
so its is possible to have duplicate Id or duplicate CLientid or duplicate Branchid but its not possible to have the whole combination asa duplicate
for example
Id Clientid Branchid
1 1 1
1 2 1
1 1 2
2 1 1
the above combination is true
but below combination is not allowed as its a primary key and cann't have duplicate values
Id Clientid Branchid
1 1 1
1 1 1
and all columns as null is also not possible as primary key doesn't allow null
I am working on a project and I realized I am unsure about how to use multiple primary keys. I have a table named "User_Details" that has the details of Customer ID, email address and password. From my understanding, I can use both Customer ID and email address as the primary key. In this case do I use only one as Primary Key or both? If I use both, do they become composite primary keys?
(PS. I have other tables, where the foreign key is the customer ID)
You can only have one primary key, but you could definitely have other unique fields.
Usually using an integer / id as primary key is preferred over a string key, and an id is presumably auto assigned, where as email could change - which would be a problem for foreign key relations.
Since you already use customer Id as a foreign key in other tables, I would suggest you continue to do that.
You can only have one primary key, but you can have multiple columns in your primary key, alternatively you can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.
Easiest way tho is a Composite Primary Key which is a primary key made from two or more columns. For example:
CREATE TABLE userdata (
userid INT,
userdataid INT,
info char(200),
primary key (userid, userdataid),
);
Here is more info: Link
You can have a Composite Primary Key which is a primary key made from two or more columns. For example:
CREATE TABLE userdata (
userid INT,
userdataid INT,
info char(200),
primary key (userid, userdataid),
);
A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.
Candidate keys are a fundamental concept in the relational data model.
It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.
I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.
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`);
...
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)
)
I came across the following SQL in a book:
CREATE TABLE 'categories'(
id SMALLINT NOT NULL AUTO INCREMENT,
category VARCHAR(30) NOT NULL,
PRIMARY KEY('id'),
UNIQUE KEY 'category'('category')
)ENGINE=MyISAM DEFAULT CHARSET = utf8;
I was wondering is there a reason why I would need a PRIMARY and UNIQUE KEY in the same table? I guess, underlying that question is, what is the difference between PRIMARY and UNIQUE keys?
The relational model says there's no essential difference between one key and another. That is, when a relation has more than one candidate key, there are no theoretical reasons for declaring that this key is more important than that key. Essentially, that means there's no theoretical reason for identifying one key as a primary key, and all the others as secondary keys. (There might be practical reasons, though.)
Many relations have more than one candidate key. For example, a relation of US states might have data like this.
State Abbr Postal Code
--
Alabama Ala. AL
Alaska Alaska AK
Arizona Ariz. AZ
...
Wyoming Wyo. WY
It's clear that values in each of those three columns are unique--there are three candidate keys.
If you were going to build a table in SQL to store those values, you might do it like this.
CREATE TABLE states (
state varchar(15) primary key,
abbr varchar(10) not null unique,
postal_code char(2) not null unique
);
And you'd do something like that because SQL doesn't have any other way to say "My table has three separate candidate keys."
I didn't have any particular reason for choosing "state" as the primary key. I could have just as easily chosen "abbr" or "postal_code". Any of those three columns can be used as the target for a foreign key reference, too.
And as far as that goes, I could have built the table like this, too.
CREATE TABLE states (
state varchar(15) not null unique,
abbr varchar(10) not null unique,
postal_code char(2) not null unique
);
I'm surprised that nobody mentionned that a primary key can be referenced as foreign key into other tables.
Also an unique constraint allows NULL values.
The reason you need two uniqueness restrictions (one being the Primary Key) is that you are using Id as a surrogate key. I.e., it is an arbitrary value that has no meaning in relation to the data itself. Without the unique key (or colloquially known as "business key" i.e, a key that the user would recognize as being enforced), a user could add two identical category values with different arbitrary Id values. Since users should never see the surrogate key, they would not know why they are seeing a duplicate even though the database would think they are different.
When using surrogate keys, having another unique constraint on something other than the surrogate key is critical to avoid duplicate data.
Depending on who you talk to and how they read the specification, Unique keys( which is redundant by the way. A "key" is by definition unique) are also not supposed to allow nulls. However, one can also read the specifications as saying that Unique constraints, unlike Primary Key constraints, are in fact supposed to allow nulls (how many nulls are allowed also varies by vendor). Most products, including MySQL, do allow nulls in Unique constraints whereas Primary Key constraints do not.
Similarity
Both a PRIMARY and UNIQUE index create a constraint that requires all values to be distinct (1).
Difference
The PRIMARY key (implicitly) defines all key columns as NOT NULL; additionally, a table can only have one primary key.
(1) Each NULL value is considered to be distinct.
A UNIQUE constraint and PRIMARY key both are similar and it provide unique enforce uniqueness of the column on which they are defined.
Some are basic differences between Primary Key and Unique key are as follows.
Primary key
Primary key cannot have a NULL value.
Each table can have only single primary key.
Primary key is implemented as indexes on the table. By default this index is clustered index.
Primary key can be related with another table's as a Foreign Key.
We can generate ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value.
Unique Constraint
Unique Constraint may have a NULL value.
Each table can have more than one Unique Constraint.
Unique Constraint is also implemented as indexes on the table. By default this index is Non-clustered index.
Unique Constraint cannot be related with another table's as a Foreign Key.
Unique Constraint doesn't support Auto Increment value.
You can find detailed information from: http://www.oracleinformation.com/2014/04/difference-between-primary-key-and-unique-key.html