Foreign key SQL syntax - sql

Let's suppose that there are two tables table1 and table2 where the second one references the first one.
I was wondering whether the following two forms of defining their foreign key relationship results in the same table structure of the second table.
CREATE TABLE table1(a INT, b INT, PRIMARY KEY(a, b));
1)
CREATE TABLE table2(a INT, b INT,
FOREIGN KEY(a, b) REFERENCES table1(a, b)
);
2)
CREATE TABLE table2(a INT, b INT,
FOREIGN KEY(a) REFERENCES table1(a),
FOREIGN KEY(b) REFERENCES table1(b)
);
I would presume that there is no difference but couldn't find any reference to support this claim.

First, this syntax is not correct:
CREATE TABLE table1 (
a INT PRIMARY KEY,
b INT PRIMARY KEY
);
A primary key is primary because only one can be defined. Presumably, you intend a composite primary key:
CREATE TABLE table1 (
a INT,
b INT,
PRIMARY KEY (a, b)
);
The foreign key relationships are entirely different. The second creates two foreign key relationships. With a composite primary key, it would fail, because the reference should be to a primary key (or at least a unique key).

Related

Sql creating table consisting of keys from other tables

this is probably a simple question but I am quite new to SQL and databases, so I have been following this site: https://www.postgresqltutorial.com/postgresql-foreign-key/ to try and create a table that consist of primary keys from other tables.
Here I have the structure of the database in an excel overview. With colors showing the relations. i am having problems with the One-To-Many tables. As I get the same error every time "ERROR: column "id" referenced in foreign key constraint does not exist
SQL state: 42703".
The SQL query:
DROP TABLE IF EXISTS ingredient_to_unit_relations;
DROP TABLE IF EXISTS ingrediens;
CREATE TABLE ingrediens (
id serial,
name_of_ingredient varchar(255),
price_per_unit int,
PRIMARY KEY (id)
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id
FOREIGN KEY (id)
REFERENCES ingrediens (id)
);
You need to define the column in order to declare it as a foreign key:
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
ingredient_id int,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingrediens (id)
);
I might recommend some somewhat different naming conventions (I changed the name id in the table above):
CREATE TABLE ingredients (
ingredient_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name varchar(255),
price_per_unit int
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ingredient_id int,
CONSTRAINT Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingredients (ingredient_id)
);
Notes:
I am a fan of naming primary keys after the table they are in. That way, foreign keys and primary keys usually have the same name (and you can use using if you choose).
Avoid SERIAL. GENERATED ALWAYS AS IDENTITY is now recommended.
You can inline primary key constraints (as well as other constraints).
There is not generally a need to repeat the table name in a column (other than the primary key). So, name instead of name_of_ingredient.
Using int for a monetary column is suspicious. It doesn't allow smaller units. That might work for some currencies but in general I would expect a numeric/decimal type.

SQL: Is creating multiple foreign keys with one statement equivalent to creating them with one statement?

For example let's have the following table definition:
CREATE TABLE table1
(
id INT UNIQUE,
name VARCHAR(100) UNIQUE,
description VARCHAR(100),
PRIMARY KEY (id, name)
);
Now I would like to create another table which would have a foreign key to the above composite primary key. Would the following two statements be equivalent?
1)
CREATE TABLE table2
(
id INT PRIMARY KEY,
table1_id INT,
table1_name VARCHAR(100),
FOREIGN KEY (table1_id) REFERENCES table1(id),
FOREIGN KEY (table1_name) REFERENCES table1(name)
);
2)
CREATE TABLE table2
(
id INT PRIMARY KEY,
table1_id INT,
table1_name VARCHAR(100),
FOREIGN KEY (table1_id, table1_name) REFERENCES table1(id, name),
);
I noticed that behind the scenes Postgre SQL creates two FK db objects in the case of 1) and one FK object in the case of 2). Would everything work the same anyway?
Not at all. A foreign key reference should be to the primary key. In this case you have a composite primary key (although that is probably not needed, see below). Although foreign key references to unique keys are allowed (and some databases even allow foreign key references to any indexed columns), that is not a best practice.
When you use a composite primary key (your second example) you are guaranteeing that id/name are aligned in the first table. When you use separate references (your first example), you do not know that they are aligned, so the id could refer to one row in table1 and the name to another row. I doubt that is your intention.
In any case, repeating redundant data among tables is a bad practice. The better data model is:
CREATE TABLE table1 (
id INT PRIMARY KEY,
name VARCHAR(100) UNIQUE,
description VARCHAR(100),
);
CREATE TABLE table2 (
id INT PRIMARY KEY,
table1_id INT,
FOREIGN KEY (table1_id) REFERENCES table1(id)
);
Then, if you want the corresponding name, look up the name in the first table.
As a note, in Postgres, I would expect the INT to really be SERIAL so the database assigns a unique, increasing value when you insert new rows.
If you actually want two references to table1 then use two id references:
CREATE TABLE table2 (
id INT PRIMARY KEY,
table1_id INT,
table1_id_2 INT,
FOREIGN KEY (table1_id) REFERENCES table1(id),
FOREIGN KEY (table1_id_2) REFERENCES table1(id)
);

SQL: Having a primary key also be a foreign key

For this question, I am referring to the specific case where you have table T, it has primary key K, but K is a foreign key. Is this valid? And how would you write it in SQL99?
All the other questions I've seen on here are just asking whether or not a primary key can be a foreign key for another table. That's not what I'm asking about. I'm asking about a table which has a foreign key where that is the primary key of that table.
If I understand you correctly, you want to create a hierarchical table, for instance:
create table hierarchical
(
id number primary key,
parent_id number
);
alter table hierarchical add constraint
fk_parent_id foreign key(parent_id) references hierarchical(id);
This kind of table can contain employees/managers for instance.
A column can be a primary key as well foreign key. For example, refer to the following:
A column can be both a primary key and a foreign key. For example:
create table A
(
id int not null
, constraint PK_A primary key (id)
);
create table B
(
id int not null
,constraint PK_B primary key (id)
,constraint FK_B_ID foreign key (id) references A(id)
);
Though, this requires data to be present in Table B first.

Can I use a compound primary key as foreign key in Oracle?

I just wanted to know if it is possible to use table A's compound primary key within table B as a foreign key.
CREATE TABLE A(
ID INT,
COD INT,
CONSTRAINT PK_INF PRIMARY KEY (ID, COD),
);
CREATE TABLE B(
REF_NUMBER INT,
NAME VARCHAR(30),
CONSTRAINT FK_INF FOREIGN KEY (REF_NUMBER) REFERENCES A(PK_INF) <- is this correct?
);
Thanks in advance.
The answer to your question is "yes", you can use a compound primary key for a foreign key reference. But, you need two columns for it. Something like this:
CREATE TABLE A(
ID INT,
COD INT,
CONSTRAINT PK_INF PRIMARY KEY (ID, COD),
);
CREATE TABLE B(
REF_ID INT,
REF_CODINT,
NAME VARCHAR(30),
CONSTRAINT FK_INF FOREIGN KEY (REF_ID, REF_COD) REFERENCES A(ID, COD) <- is this correct?
);

Referencing a two column primary key with multiple foreign keys

Take the following two tables in Oracle:
Create Table A
( A int, B int, C int,
Constraint pk_ab Primary Key(A, B),
Unique (C)
);
Create Table B
( D int, E int, F int,
Constraint fk_d Foreign Key (D) References A(A),
Constraint fk_e Foreign Key (E) References A(B)
);
Why doesn't this statement work? Or more specifically, why shouldn't it work? The reason I'm trying to create this type of relation is say, in the future, I want to delete B.D, but keep the relation FK_E.
I'm getting the error:
ORA-02270: no matching unique or primary key for this column-list
"Why doesn't this statement work? Or more specifically, why shouldn't
it work? "
You have defined the primary key on A as a compound of two columns (A,B). Any foreign key which references PK_AB must match those columns in number. This is because a foreign key must identify a single row in the referenced table which owns any given row in the child table. The compound primary key means column A.A can contain duplicate values and so can column A.B; only the permutations of (A,B) are unique. Consequently the referencing foreign key needs two columns.
Create Table B
( D int, E int, F int,
Constraint fk_de Foreign Key (D,E) References A(A,B)
);
"Since there are multiple PK's that table B references"
Wrong. B references a single primary key, which happens to comprise more than one column,
" say, in the future, I want to delete B.D, but keep the relation
fk_e. "
That doesn't make sense. Think of it this way: D is not a property of B, it is an attribute B inherits through its dependence on table A.
One way to avoid this situation is to use a surrogate (or synthetic) key. Compound keys are often business keys, hence their columns are meaningful in a business context. One feature of meaningful column values is that they can change, and cascading such changes to foreign keys can be messy.
Implementing a surrogate key would look like this:
Create Table A
( id int not null, A int, B int, C int,
Constraint pk_a Primary Key(ID),
constraint uk_ab Unique (A,B)
);
Create Table B
( a_id int, F int,
Constraint fk_n_a Foreign Key (A_ID) References A(ID)
);
Of course, you could kind of do this using the schema you posted, as you already have a single column constraint on A(C). However, I think it is bad practice to reference unique constraints rather than primary keys, even though it's allowed. I think this partly because unique constraints often enforce a business key, hence meaning, hence the potential for change, but mainly because referencing primary keys just is the industry standard.
Try create two separate indexes for column's A and B before creating table B
CREATE INDEX a_idx ON A (A);
CREATE INDEX b_idx ON A (B);
But probably you need a compound FK on table B
Create Table B
( D int, E int, F int,
Constraint fk_d Foreign Key (D,E) References A(A,B)
);
A foreign key always references a PK of another table. Neither A nor B
alone are PK's.. You have multiple PK's.
Constraint fk_d Foreign Key (D,E) References A(A,B)
Also the database cannot validate a partial null multiple foreign key, so I think the check constraint also needs to be added to the table.
alter table B add constraint check_nullness
check ( ( D is not null and E is not null ) or
( D is null and E is null ) )