I have a scenario where have two tables with unique elements and both the tables contains same sort of records. Now one table is having primary key and another doesn't. so what is the advantage of having primary key in case i have unique elements in both the tables. and how primary key is related with index.?
I have been asked this question in Nokia interview. pretty confusing please answers with some sort of example.
what is the advantage of having primary key?
Primary key induces or rather forces the column to have two conditions-
UNIQUE VALUE
NOT NULL
So when a table row is inserted it must follow both conditions. In case the table has some records already it will check for uniqueness while adding the constraint. If there are duplicate entries for that attribute then you cant add the primary key constraint.
how primary key is related with index.?
When you declare an attribute as PRIMARY KEY indexing will be created on that attribute by default.
This helps in faster access to the records when the number of records is too high. (=> faster fetching).
But for a small table indexing would slow down things as it needs to update the indexes every time you insert/update a row.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Primary key:
Used to serve as a unique identifier for each row in a table.
Cannot accept NULL values.
Creates clustered index.
Only one primary key
Unique key:
Used to serve as a unique identifier for a row in a table.
Can accept one NULL value.
Creates non-clustered index
More than one unique key
Almost we are using the primary key to identify each row uniquely so the unique key as well.
I am not sure If I am right or wrong, But If we create a unique key with not null constraint would provide almost the same behavior which is provided by the primary key.
For example:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int);
So why do we really need a primary key, as a unique key can help us achieve whatever we want?
We can also use a unique key as a foreign key to the reference table as well.
A lot of relational purists regard the elevation of one key as the "primary key" as a mistake1 and believe that all candidate keys should be treated equally. If you're of that school of thought (as you appear to be) then you're correct, you don't need a PK.
1In the design of SQL itself, in having this feature.
Similarly, theorists see no problem with keys consisting of zero columns (a table with that key declared does make sense, and can only contain 0 or 1 row). But here SQL will prevent you from declaring such a key.
It's true that a UNIQUE KEY on NOT NULL column(s) does fill the same role as a PRIMARY KEY.
Folks should remember that a primary key is a constraint, and may be defined on multiple columns. Primary key does not have to be a single-column auto-inc integer.
In MySQL's InnoDB engine, the table is stored as a clustered index by its primary key, or if it doesn't have a primary key, then it's a clustered index by its first non-null unique key. (a table can have multiple unique keys). See https://dev.mysql.com/doc/refman/8.0/en/innodb-index-types.html
But isn't it quicker and more clear to say the clustered index is by the primary key? :-)
There is a semantic difference.
Ignoring the minor differences such as handling of NULL's, a primary key is essentially a unique constraint, but is simply designated as the primary one. It's the one true way to identify a given row. If I had a particular row that I wanted you to see, what would I tell you about the row to make sure you look at the exact same row? I'd tell you the primary key. "Hey, I think we have a problem with row # 78. Can you look at row # 78?" There might be other unique constraints on the table, but the PK is the go-to.
The primary key is the canonical identification of a row. It might be a single column or a combination of columns. It is entirely possible, valid, and common, to have a primary key and no unique constraints.
Practical Considerations
Anecdotally, foreign keys very often map rows across tables and therefore the primary key of a table is likely to be repeated across tables. When doing an update of the value, therefore, foreign keys get impacted. Due to this, it is often desirable to have an immutable primary key. So-called surrogate keys are popular for this reason, though there are schools of thought on that subject. [1]
Documentation tools typically inspect primary keys and foreign keys in order to determine the relationships between tables. For example, you can auto-generate an ER diagram by traversing the FK to PK relationships.
[1] With that said, keep in mind that foreign keys can point to any column of any table, including the same table. Pointing to the primary key of a table is extremely common because it usually makes the most sense, but there are cases where it does not make sense.
Although of similar definitions, they have different applications. The primary key is a column that serves to uniquely identify each tuple in the table. Furthermore, it adds integrity constraints to the table and maintains the relationship with foreign keys. The unique key is simpler, it only serves to uniquely identify a tuple in the table.
When should I use KEY, PRIMARY KEY, UNIQUE KEY and INDEX?
KEY and INDEX are synonyms in MySQL. They mean the same thing. In databases you would use indexes to improve the speed of data retrieval. An index is typically created on columns used in JOIN, WHERE, and ORDER BY clauses.
Imagine you have a table called users and you want to search for all the users which have the last name 'Smith'. Without an index, the database would have to go through all the records of the table: this is slow, because the more records you have in your database, the more work it has to do to find the result. On the other hand, an index will help the database skip quickly to the relevant pages where the 'Smith' records are held. This is very similar to how we, humans, go through a phone book directory to find someone by the last name: We don't start searching through the directory from cover to cover, as long we inserted the information in some order that we can use to skip quickly to the 'S' pages.
Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row. It is a special case of unique key. A table can have at most one primary key, but more than one unique key. When you specify a unique key on a column, no two distinct rows in a table can have the same value.
Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.
KEY and INDEX are synonyms.
You should add an index when performance measurements and EXPLAIN shows you that the query is inefficient because of a missing index. Adding an index can improve the performance of queries (but it can slow down modifications to the table).
You should use UNIQUE when you want to contrain the values in that column (or columns) to be unique, so that attempts to insert duplicate values result in an error.
A PRIMARY KEY is both a unique constraint and it also implies that the column is NOT NULL. It is used to give an identity to each row. This can be useful for joining with another table via a foreign key constraint. While it is not required for a table to have a PRIMARY KEY it is usually a good idea.
Primary key does not allow NULL values, but unique key allows NULL values.
We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).
PRIMARY KEY AND UNIQUE KEY are similar except it has different functions. Primary key makes the table row unique (i.e, there cannot be 2 row with the exact same key). You can only have 1 primary key in a database table.
Unique key makes the table column in a table row unique (i.e., no 2 table row may have the same exact value). You can have more than 1 unique key table column (unlike primary key which means only 1 table column in the table is unique).
INDEX also creates uniqueness. MySQL (example) will create a indexing table for the column that is indexed. This way, it's easier to retrieve the table row value when the query is queried on that indexed table column. The disadvantage is that if you do many updating/deleting/create, MySQL has to manage the indexing tables (and that can be a performance bottleneck).
Hope this helps.
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.
The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.
Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table.
column take unique values (not same) when we applied primary & unique key.
Unique Key :
More than one value can be null.
No two tuples can have same values in unique key.
One or more unique keys can be combined to form a primary key, but not vice versa.
Primary Key
Can contain more than one unique keys.
Uniquely represents a tuple.
If I have a table that has a primary key and a foreign key, and searches are frequently done with queries that include both (...WHERE primary=n AND foreign=x), is there any performance benefit to making a multiple index in MySQL using the two keys?
I understand that they are both indexes already, but I am uncertain if the foreign key is still seen as an index when included in another table. For example, would MySQL go to the primary key, and then compare all values of the foreign key until the right one is found, or does it already know where it is because the foreign key is also an index?
Update: I am using InnoDB tables.
For equality comparisons, you cannot get an improvement over the primary key index (because at that point, there is at most just one row that can match).
The access path would be:
look at the primary key index for primary = n
get the single matching row from the table
check any other conditions using the row in the table
A composite index might make some sense if you have a range scan on the primary key and want to narrow that down by the other column.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
mySQL's KEY keyword?
Like
PRIMARY KEY (ID),
KEY name (name),
KEY desc (desc),
etc.
what are they useful for?
Keys are used to enforce referential integrity in your database.
A primary key is, as its name suggests, the primary identification of a given row in your table. That is, each row's primary key will uniquely identify that row.
A unique key is a key that enforces uniqueness on that set of columns. It is similar to a primary key in that it will also uniquely identify a row in a table. However, there is the added benefit of allowing NULL in some of those combinations. There can only be 1 primary key, but you can have many unique keys.
A foreign key is used to enforce a relationship between 2 tables (think parent/child table). That way, a child table can not have a value of X in its parent column unless X actually appears in the parent table. This prevents orphaned records from appearing.
The primary key constraint ensures that the column(s) are:
not null
unique (unique sets if more than one column)
KEY is MySQL's terminology in CREATE TABLE statements for an index. Indexes are not ANSI currently, but all databases use indexes to speed up data retrieval (at the cost of insertion/update/deletion, because of maintenance to keep the index relevant).
There are other key constraints:
unique
foreign key (for referential integrity)
...but your question doesn't include examples of them.
keys are also called indexes. They are used for speeding up queries. Additionally keys can be constrains (unique key and foreign key). The primary key is also unique key and it identifies the records. The record can have other unique keys as well, that do not allow to duplicate a value in a given column. Foreign key enforces referential integrity (#Derek Kromm already wrote excellent description). The ordinary key is used only for speeding up queries. You need to index the columns used in the WHERE clause of the queries. If you have no index on the column, MySQL will need to read the whole table to find the records you need. When index is used, MySQL reads only the index (which is usually a B+ tree) and then read only those record from the table it found in the index.
Primary KEY is for creating unique/not null constraint for each row in the table. Also searching by this key is the fastest. You can create only one PK in the table.
Ordinary key/index is key for speeding your searching by this column, sorting, grouping and joining with other table by this key.
Indexes drawback:
Adding new indexes to table will influence on speed or running insert/update/delete statements. So you should select columns for indexing in your table very carefully.
Key are used for relation purposes between tables and you are able to create joins in order to select data from multiple tables
What, you didn't fine the wikipedia entry comprehensive? ;-)
So, a key, in a relational database (such as MySQL, PostgreSQL, Oracle, etc) is a data constraint on a column or set of columns. The most common keys are the Primary key and foreign keys and unique keys.
A foreign key specifically relates the data of one table to data in another table. You might see that a table blog_posts has a foreign key to users based on a user_id column. This means that every user_id in blog_posts will have a corresponding entry in the users column (this is a one-to-many relationship -- a topic for another time).
If a column (or group of columns) has a unique key, that means that there can only be one such incidence of the key in the table. Often you'll see things like email addresses be unique keys -- you only want one email address per user. I've also seen a combination of columns match to a unique key -- the five columns, first_name, last_name, address, city, and state, will often be a unique key -- realistically, there can only be one William Gates at 1835 73rd Ave NE, Medina, Washington. (I do realize that it is possible for a William Gates Jr. to be born, but the designers of that database didn't really care).
The primary key is the primary, unique identifier of a given table. By definition it is a unique key. It is something which cannot be null and must be unique. It holds a special place of prominence among the indexes of a given table.
When should I use KEY, PRIMARY KEY, UNIQUE KEY and INDEX?
KEY and INDEX are synonyms in MySQL. They mean the same thing. In databases you would use indexes to improve the speed of data retrieval. An index is typically created on columns used in JOIN, WHERE, and ORDER BY clauses.
Imagine you have a table called users and you want to search for all the users which have the last name 'Smith'. Without an index, the database would have to go through all the records of the table: this is slow, because the more records you have in your database, the more work it has to do to find the result. On the other hand, an index will help the database skip quickly to the relevant pages where the 'Smith' records are held. This is very similar to how we, humans, go through a phone book directory to find someone by the last name: We don't start searching through the directory from cover to cover, as long we inserted the information in some order that we can use to skip quickly to the 'S' pages.
Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row. It is a special case of unique key. A table can have at most one primary key, but more than one unique key. When you specify a unique key on a column, no two distinct rows in a table can have the same value.
Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.
KEY and INDEX are synonyms.
You should add an index when performance measurements and EXPLAIN shows you that the query is inefficient because of a missing index. Adding an index can improve the performance of queries (but it can slow down modifications to the table).
You should use UNIQUE when you want to contrain the values in that column (or columns) to be unique, so that attempts to insert duplicate values result in an error.
A PRIMARY KEY is both a unique constraint and it also implies that the column is NOT NULL. It is used to give an identity to each row. This can be useful for joining with another table via a foreign key constraint. While it is not required for a table to have a PRIMARY KEY it is usually a good idea.
Primary key does not allow NULL values, but unique key allows NULL values.
We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).
PRIMARY KEY AND UNIQUE KEY are similar except it has different functions. Primary key makes the table row unique (i.e, there cannot be 2 row with the exact same key). You can only have 1 primary key in a database table.
Unique key makes the table column in a table row unique (i.e., no 2 table row may have the same exact value). You can have more than 1 unique key table column (unlike primary key which means only 1 table column in the table is unique).
INDEX also creates uniqueness. MySQL (example) will create a indexing table for the column that is indexed. This way, it's easier to retrieve the table row value when the query is queried on that indexed table column. The disadvantage is that if you do many updating/deleting/create, MySQL has to manage the indexing tables (and that can be a performance bottleneck).
Hope this helps.
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.
The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.
Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table.
column take unique values (not same) when we applied primary & unique key.
Unique Key :
More than one value can be null.
No two tuples can have same values in unique key.
One or more unique keys can be combined to form a primary key, but not vice versa.
Primary Key
Can contain more than one unique keys.
Uniquely represents a tuple.