Using a foreign key as part of a composite primary key - sql

I have two tables in SQL Server. The first is all the 1:1 relationships that belong to individual jobs, which has the primary key declared as follows:
CREATE TABLE Jobs(
JobNumber bigint PRIMARY KEY )
The second table is the list of all of the jobs' components and their 1:1 relationships.
Each component refers to a single job by its job number, which is a foreign key, and multiple components may refer to the same job. Components are numbered within jobs as 1, 2, 3 and so on.
Is it possible and reasonable to use the column JobNumber (foreign key) within a composite primary key in the 2nd table, so that the primary key would be made up of (JobNumber, ComponentNumber) as follows:
CREATE TABLE Components(
JobNumber bigint FOREIGN KEY REFERENCES Jobs(JobNumber) NOT NULL,
ComponentNumber int NOT NULL,
PRIMARY KEY(JobNumber, ComponentNumber)
)
The other option is, of course, to use a surrogate primary key, but this would not enforce the uniqueness constraint on the combination of JobNumber and ComponentNumber (two records in the 2nd table could have JobNumber=1 and ComponentNumber=1, for example), so I would prefer to use a composite natural primary key.

Sure, why not? I don't see any reason not to use the composite primary key!
The only minor drawback is that any other table that needs to reference your Components table now also must use both columns to establish a foreign key relationship - you cannot reference only half of the primary key of a table.
Also: if you would choose to use a separate surrogate column as your PK, you can always enforce uniqueness with a unique constraint on (JobNumber, ComponentNumber) ....

Related

Difference Between Unique And Composite Primary key In sql server

I want to know what is the difference between unique key and composite primary key in SQL Server.
According to w3c school:
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
We can create composite primary key by using this:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
For composite primary key syntax:
CREATE TABLE Persons
(
P_Id int,
C_Id int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Primary Key (P_Id,C_Id)
);
The UNIQUE constraint uniquely identifies each record in a database table. This provide a guarantee for uniqueness for a column or set of columns. We can define(point) a single row with this.
A PRIMARY KEY has a UNIQUE constraint by default.
While in some tables, there won't be any columns with a unique value to define a row. In such cases COMPOSITE KEYs are used. In such cases two or more columns are combined together so that this combination is unique.
As you said yourself, the only difference between a unique and a primary key is that there may only be 1 primary key on a table while it can have more unique keys.
Furthermore, the values of a primary key may not be null.
Both unique- and primary keys can be composed of multiple columns (composed key).
By the ways, in your example you had a unique key on the P_Id column and a composed primary key that includes that very same column.
This has no sense.
I would suggest to create only a simple primary key on that P_Id column.
Composite keys are formed of more than one column
Primary key prevents a second row on that table with same key column values.
A Primary key can be formed of a single column and as well as of more than one column. So primary key can be defined as a composite key too.
The primary key does not accept the any duplicate and NULL values.
A primary key of one table can be referenced by foreign key of another table. A table can have more than one unique key unlike primary key. Unique key constraints can accept only one NULL value for column. Unique constraints are also referenced by the foreign key of another table. A composite key is having two or more attributes that together can uniquely identify a tuple in a table. Such a key is also known as Compound Key, where each attribute creating a key is a foreign key in its own right.

Should I use a compound primary key here or is UNIQUE(fk1, fk2) a better design?

I am not very experienced with SQL and therefore I have troubles when it comes to decision making from time to time. What I am having are the tables shop, language and shop_supported_language.
CREATE TABLE shop (
-- PRIMARY KEY
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE language (
-- PRIMARY KEY
id BIGSERIAL PRIMARY KEY,
-- ATTRIBUTES
code CHAR(5) NOT NULL,
UNIQUE (code)
);
CREATE TABLE shop_supported_language (
-- PRIMARY KEY
id BIGSERIAL PRIMARY KEY,
-- FOREIGN KEYS
shop_id BIGINT NOT NULL,
CONSTRAINT fk__shop_supported_language__shop
FOREIGN KEY (shop_id)
REFERENCES shop(id),
language_id BIGINT NOT NULL,
CONSTRAINT fk__shop_supported_language__language
FOREIGN KEY (language_id)
REFERENCES language(id)
-- Would definitely not hurt:
-- UNIQUE(shop_id, language_id)
);
As the name suggests, shop_supported_language represents the languages that a shop is actually supporting. A shop can decide in what translations it wants to provide e.g.
CREATE TABLE shop_offer_details (
-- PRIMARY KEY
id BIGSERIAL PRIMARY KEY,
-- FOREIGN KEYS
shop_offer_id BIGINT NOT NULL,
-- ...
shop_supported_language_id BIGINT NOT NULL,
CONSTRAINT fk__shop_offer_details__shop_supported_language
FOREIGN KEY (shop_supported_language_id)
REFERENCES shop_supported_language(id),
-- ...
);
Is it a good idea to not have a compound primary key for shop_supported_language? Imho it would make sense to set a UNIQUE constraint to shop_id and language_id and I'm good.
Since this is a core element in my database I would like to know if what I am doing is basically okay or fundamentally dangerous.
The reason why I don't want to use that compound PK is actually shop_offer_details. In that case I don't have to reference a compound PK. Would that be an argument against the compound PK?
If shop table has a shop_id that uniquely identifies the shop and if language table has a language_id that uniquely identifies the language and the relationship between those 2 tables is that a shop can support many languages and a language can be supported by many shops (many to many), then it should be fine to use shop_id and language_id as the 2 keys to identify what shop support what language and what language is used by what shops. I don't see a need to generate another key to identify the many to many relationship (shop_id and language_id).
There seem to be three (candidate and/or super-) key issues muddled here: PRIMARY KEY vs UNIQUE NOT NULL keys, simple vs composite keys and natural vs surrogate keys.
A PRIMARY KEY constraint is just one of whatever UNIQUE NOT NULL constraints you have that you decided to call "primary". There's no constraint difference between declaring (FK1, FK2) a PRIMARY KEY or a UNIQUE NOT NULL key. There might be project heuristics about when to use one over the other (eg declaring a key as PRIMARY KEY when it's the one to be used as FOREIGN KEY when you have a choice or having small values as keys for performance) and the DBMS might treat it differently (eg indexing it by default). There's no role for PRIMARY KEYs in relational theory.
There is also nothing wrong per se with composite keys. There are reasons for adding a simple surrogate candidate key then also using it as foreign key. Some of which are re implementation and need to be shown worth-while. And some of which are for good logical design, eg when a distinguishing id must be introduced after the system starts up or to sheild from changes in what columns are available for natural keys.

SQL - Unique Key, Primary Key & Foreign Key

What are the differences between Unique Key, Primary Key and Foreign Key with respect to concept of SQL?
How they are different from each other?
A PRIMARY Key and UNIQUE Key constraints both are similar and it provide unique enforce uniqueness of the column on which they are defined.
Primary Key
Primary key cannot have a NULL value.
Each table can have only one primary key.
By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.
Primary key can be related with another table's as a Foreign Key.
We can generated ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value.
Unique Key
Unique Constraint may have a NULL value.
Each table can have more than one Unique Constraint.
By default, Unique key is a unique non-clustered index.
Unique Constraint can not be related with another table's as a Foreign Key.
Unique Constraint doesn't supports Auto Increment value.
Foreign Key
Foreign key is a field in the table that is primary key in another table.
Foreign key can accept multiple null value.
Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.
We can have more than one foreign key in a table.
There are actual advantages to having a foreign key be supported with a clustered index, but you get only one per table. What's the advantage? If you are selecting the parent plus all child records, you want the child records next to each other. This is easy to accomplish using a clustered index.
Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child] is what would be referred to as an "orphan record". Think long and hard before doing this.
Note: we use constraint for enforce data integrity
Primary Key
1)can't insert null value
2) one table have one primary key
Unique key
1) insert null value one at time
2)one table have multiple unique key
3) you can refereed as candidate key also
foreign key
1) maintain the relationship between two table and also multiple
Note: without any constraint you get data in multiple table but you can not get data peoperly
A note about Unique key
The parent table in a Primary Key-Foreign Key relation is normally called as Primary Key table but PK is not mandatory in a parent table. A unique key/constraint in parent table is sufficient. As PK is always unique, it is often used as foreign key in another table. see this SO post

Is there always a need for a Primary Key in sql table creations?

I don't know if I created these tables in sql correctly. Can someone confirm I am doing this correctly or incorrectly? Can a table just have a foreign key or does it have to have a primary key? Thanks in advance.
CREATE TABLE Job(
JobId integer,
ToolName varchar(40),
status varchar(100),
start_time time,
finish_time time
PRIMARY KEY(JobId));
CREATE TABLE ErrorLog(
JobId integer,
ErrCode integer,
Description varchar(200),
PRIMARY KEY(ErrCode)
FOREIGN KEY(JobId) REFERENCES Job(JobId));
CREATE TABLE BLAST(
input varchar(100),
database varchar(100),
evalue varchar(100),
JobId integer,
FOREIGN KEY (JobId) REFERENCES Job(JobId));
CREATE TABLE MitoLoc(
input varchar(100),
specificity varchar(100),
JobId integer,
FOREIGN KEY (JobId) REFERENCES Job(JobId));
It is best practice to create a primary key column on a table in a SQL RDBMS. Although SQL does not require tables to have primary keys.
Primary keys allow for a unique identifier to be set for each row in the table. This is the only way you can uniquely identify a specific row in the table, and the only way you'll be able to utilize a foreign key relationship.
Database servers, like SQL Server, also optimize both the storage and querying of tables better when they have primary keys defined.
Primary keys are a very good idea, but not required. Almost every table that I create has an automatically incremented primary key. This is in addition to several other columns that I keep around, such as CreatedAt and CreatedBy.
Foreign key relationships are typically to primary keys but can also be to unique keys.
Why do you want a primary key?
So you can delete a row that is a duplicate, easily.
So you can readily update a single row.
An auto incremented primary key gives you an idea of the order that rows were inserted into the table.
A single column primary key is much easier to handle with foreign key references.
There are, undoubtedly, other reasons. But those are a few.
As for your tables, I think Mitoch and Blast should have id columns that are primary keys. You can also declare other columns (or combinations) to be unique, if appropriate.
Not needed. But It is not good for table structure.
you can create tables without primary key. and it can be have foreign key.
But some DBMS don't allow to save table without primary key
if you are not using primary key then
It is difficult to identify each record
Its record can't references to other tables
when creating table structure some time you have to create composite primary key that mean two or more columns together (combination ) can be primary key

Primary Key In SQL

I want to know if it is possible to create more than one primary key in standard SQL. I mean something like that:
CREATE TABLE(Surname CHAR(100) PRIMARY KEY, Name CHAR(100) PRIMARY KEY)
Is that legal in SQL? If not, please link me a reference to the standard that says that is not possible...
Edit after the question has been clarified.
The definition of a primary key is that there is one and only one. So, no you cannot create two primary keys on two different columm.
You can however create a primary key on one column and a unique constraint on another:
create table person
(
surname varchar(100) not null primary key,
name varchar(100) not null,
constraint only_one_name unique (name)
);
The above is standard SQL for all I know.
Here is a link to the book "SQL-99, Complete" which re-states the SQL standard in a more pragmatic way: https://mariadb.com/kb/en/constraint_type-primary-key-constraint/
Quote from the book:
A Base table may be constrained by no more than one PRIMARY KEY Constraint
The original wording from the SQL standard (which is not free, so no one can give you a link to that):
A <table definition> shall specify at most one implicit or explicit <unique constraint definition> that specifies PRIMARY KEY.
(Emphasis mine)
Note that you almost never want char - especially not with a length greater than just two or three characters. The CHAR datatype pads all values to the defined length. So if you inserted the value 'FOO' into a CHAR(10) column it will (has to) be stored as 'FOO '
No, It's not legal to create two primary keys in SQL, If you are able to create two separate primary keys then it's not a primary key anymore.
You can create a composite primary keys, like primary key(surname, name) for e.g. but this will be never applicable not good pratice, primary key on name and surname.
No - but you can have a single primary key that is a combination of multiple columns:
From MSDN:
A table typically has a column or combination of columns that contain values that uniquely identify each row in the table. This column, or columns, is called the primary key (PK) of the table and enforces the entity integrity of the table. You can create a primary key by defining a PRIMARY KEY constraint when you create or modify a table.
A table can have only one PRIMARY KEY constraint, and a column that participates in the PRIMARY KEY constraint cannot accept null values. Because PRIMARY KEY constraints guarantee unique data, they are frequently defined on an identity column.
This is a bit pedantic, but of course you cannot create more than one primary key, just like there cannot be more than one tallest person in the room. But you can, (and many times should), create more than one unique key. and, except for one minor distinction there is no functional difference between them. A unique key can be used as the target of a FK constraint, or in joins just like a primary key can.
you can only have one primary key, but this primary key can be made by N columns.
example:
create table "TABLE NAME"(
"Surname" CHAR(100),
"Name" CHAR(100),
primary key ("Surname", "Name")
);
You can have a primary key containing multiple columns. This is often done in attributive tables, where one part of the key contains the id of the record in the table you're attributing to.
You can't have more than one primary key simply because it is ranked as 'the most important'. There can't be two things 'most important'.