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

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

Related

There are no primary or candidate keys in the referenced table ' ' that match the referencing column list in the foreign key

Okay so I googled and found an endless amount of results obviously, but none of them were helpful.
The error seem to be self explanatory... but I don't see what I'm doing wrong in this case:
CREATE TABLE Contrat
(ID_contrat int identity(1,1),
ID_client int,
code_contrat int,
date_début date,
date_fin date,
status_contrat varchar(20),
Totalité int,
montant_mensuel int,
CONSTRAINT PK_composed2 primary key(ID_contrat,ID_client,code_contrat),
CONSTRAINT FK_3 foreign key(code_contrat) references type_contract(code_type_contract) ON DELETE CASCADE,
CONSTRAINT FK_4 foreign key(ID_Client) references Clients(ID_Client) ON DELETE CASCADE
)
CREATE TABLE FonctionContract
(ID_FonctionContract int identity(1,1),
ID_contract int,
ID_fonction int,
nombre int,
prix_unitaire numeric(16,2),
Constraint PK_composed primary key(ID_fonctionContract, ID_Contract, ID_Fonction),
Constraint FK_11 foreign key(ID_contract) references Contrat(ID_contrat) ON DELETE CASCADE,
Constraint FK_2 foreign key(ID_Fonction) references Fonction(ID_fonction) ON DELETE CASCADE
)
The error is occuring in the before last line (FK_11).
Some results says that I should do a composed foreign key too, but I don't see how when I have ID_FonctionContract not being linked anywhere.
Each value of a Foreign Key constraint needs to reference exactly one row of the target table, and the DBMS needs to be able to guarantee this based on the table definitions.
Although the ID_contrat column is defined as auto-incremented, it is not constrained to be unique, because you've defined a multi-column Primary Key on the Contrat table. So the DBMS is saying that a single ID_contrat in your proposed Foreign Key could potentially match multiple rows in the Contrat table, which is not allowed. (This seems surprising, because you probably know that it will only match one, but the DBMS doesn't!)
You need to do one of two things:
Define your foreign key across multiple columns, so that it matches the multiple columns guaranteed to be unique on the other table; that will require you to have all three columns in the FonctionContrat table (ID_contrat, ID_client, and code_contrat)
Adjust the definition of the Contrat table to say that ID_contrat is in fact unique across all rows, either by changing the Primary Key definition, or adding an additional Unique Constraint on the ID_contrat column
I suspect the second option is the appropriate one here: it's rather unusual to use an auto-increment column and then insert duplicates into it.
What you possibly intended was two different unique constraints / indexes: one on ID_contrat and a separate one on combinations of ID_client and code_contrat. Only one of those can be marked as the Primary Key, but the other can be a Unique Index, which has most of the same functionality in practice; either one can be marked "clustered", which tells SQL Server to physically lay out the table based on that column.

what is meaning of oracle database query: primary key references t_name(col_name)?

create table books
(
bid number(5) primary key,
name varchar2(30)
);
create table members
(
mid number(5) primary key,
name varchar2(30)
);
create table issues
(
bid number(5) primary key
references books(bid),
mid number(5)
references members (mid)
);
I have 3 tables first two tables are simple but what is the meaning of third table as I know foreign key references t_name(col_name); but what is meaning of primary key references t_name(col_name) and col_name references t_name(col_name); ?
It is no special case. Here the primary key bid of table issues is referencing to the column bid of table books. This simply means that bid of issues will have only those values which are present in bid of books. It will act as the primary key of table issues so it will have unique value and it's values will be limited to those contained in books table.
So it simply means it is primary key value with it's values in table books.
It is the same as any other references statement. This is saying that the primary key also references Books(bid).
I can think of two reasons why this type of construct would be used. First, the "issues" entity could be a subset of the "book" entity. This would allow additional issues-specific columns to be stored in issues, without cluttering up books. It also allows foreign keys to either issues or books.
The second reason is that this is one way of implementing vertical partitioning. This occurs when a table has a lots of columns. For performance reasons, you want to separate them into different storage areas. This is sort of similar to what columnar databases do, but it has the overhead of the additional primary key.

Using a foreign key as part of a composite primary key

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

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'.

How Can I Reference Multiple Primary Keys For A Vector Type Primary Key

I have the following scenario: a table of projects and a table of persons, working on one or several projects. Also, I have a project id column (of type int), in the first table, which is a primary key there and I have a vector of project ids, as a column of type int, in my second table (persons), that references primary keys from the first table.
What is the correct syntax for referencing multiple primary keys, from a vector foreign key.
This is the way I am trying to create the table, but I am not sure what to place at the indicated line:
CREATE TABLE Persons(
Person_Id int,
...,
ProjectsList int[],
FOREIGN KEY (ProjectsList) REFERENCES Projects(Project_id) -- not sure what how to define the link here
);
I hope my explanations are not over-complicated. Thank you in advance for helping!
I assume you're using PostgreSQL, since that's one of the rare databases that supports array data types.
There is no syntax for declaring a foreign key that applies to the elements of an array.
You could write a trigger or a CHECK constraint as mentioned here.
But the better solution is to add a table to implement the many-to-many relationship between Projects and Persons, as Lukáš Lalinský shows. This supports First Normal Form.
No database I know can do that (using real foreign keys, not some custom triggers). You might want to normalize the tables:
CREATE TABLE Persons (
Person_ID int,
...
PRIMARY KEY (Person_ID)
);
CREATE TABLE PersonProjects (
Person_ID int,
Project_ID int,
PRIMARY KEY (Person_ID, Project_id),
FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID),
FOREIGN KEY (Project_ID) REFERENCES Projects(Project_ID)
);