relationships in Sql - sql

I know how to create one to many, many to many relationships in SQL Server, but is it possible to create one to one relationship? And is it possible to create 1 to 0 or 1 relationship?

Yes, just put PRIMARY KEYs of both entities into a link table, defining a UNIQUE key on both entities:
myrel(entityA, entityB, UNIQUE(entityA), UNIQUE(entityB))
Thus, if entityA = 1 is related to entityB = 2:
entityA entityB
1 2
, you can relate neither entityA = 1 to any other entityB, nor an entityB = 2 to any other entityA.
If you relation is symmetrical (i. e. entityA and entityB belong to same domain and relating entityA to entityB also means relating entityB to entityA), then define an additional CHECK constrant:
entityA entityB
UNIQUE(entityA)
UNIQUE(entityB)
CHECK(entityA < entityB)
and transform the normalized relation to a canonical one with this query:
SELECT entityA, entityB
FROM myrel
UNION
SELECT entityB, entityA
FROM myrel
This is a (0-1):(0-1) relation.
If you want it to be a 1:1 relation, define this table to be a domain for both entityA and entityB:
myrel(entityA, entityB, UNIQUE(entityA), UNIQUE(entityB))
A(id, PRIMARY KEY(id), FOREIGN KEY(id) REFERENCES myrel (entityA))
B(id, PRIMARY KEY(id), FOREIGN KEY(id) REFERENCES myrel (entityB))
By removing the FOREIGN KEY from either table's definition, you change the corresponding part of the relationship from 1 to (0-1).

Two ways:
1) a pk-pk 1:1 relationship. Table A and B have both a PK. Create an FK from the B PK to the PK of A. This makes 'B' the FK side of the 1:1 relationship
or
2) an FK/UC-PK 1:1 relationship. Table A has a PK and table B has a foreign key to A, but the FK in B is not on the PK of B. Now create a UC on the FK field(s) in B.

Yes, just make the Primary or alternate Key in the dependant table a Foreign Key to the Primary Key in the parent Table.

It's fun but it my favorite questions on interview.
So You have table A, B corresponding each of them has primary key A_ID, B_ID. Add foreign key to any. Let it be B: A_REF, so you just need add unique constraint onto A_REF.

Yes
TableA
id PK
TableB
id PK FK TableA

Related

Relation from one table to another with two columns in the primary key in SQL Server

I am trying to make a relation from a table to another like the following :
Books
IdBook (primary)
SerialNumber (primary)
NameBook
The other table is :
Qtt
IdQtt (primary)
IdBook
Qtt
How can I make a relation only between Qtt.IdBook and Books.IdBook ?
You meant to create a FOREIGN KEY relationship between the tables on that column like
CONSTRAINT FK_idbook FOREIGN KEY (IdBook)
REFERENCES Books (IdBook)
ON DELETE CASCADE
ON UPDATE CASCADE
But that will not work since you have composite PK in your Books table on IdBook, SerialNumber and thus you need another key column in your Qtt table to refer to both PK column else it would be a PFD (partial functional dependency)
constraint FK_book FOREIGN KEY (IdBook,IdQtt) references Books (IdBook,SerialNumber)
Although it is technically possible to create a UNIQUE constraint on Books.IdBook and a FOREIGN KEY constraint on Qtt.Book referencing that column, this probably won't work with your data model because IdBook alone doesn't uniquely identify a Books row. You need a table like BookTitle keyed by IdBook, with a one-to-many relationship to Books and another one-to-many relationship from BookTitle to Qtt on IdBook.

How can I tell the parent table from the child table in a parent/child pair? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Given a pair of tables in a parent/child relationship, how can I tell which table is the parent and which is the child?
In most cases, if the tables have referential integrity in place, you can examine the foreign keys to identify parent-child relationships. The child table has the foreign key which references the parent. This way, all children of the same parent will have the same value for the foreign key.
For example in the following relationship:
CREATE TABLE Table1
(
-- Key for Parent
Table1ID INT CONSTRAINT PK_Table1 PRIMARY KEY,
);
CREATE TABLE Table2
(
-- Key for Child
Table2ID INT CONSTRAINT PK_Table2 PRIMARY KEY,
-- Foreign Key to Parent
Table1ID INT CONSTRAINT FK_Table2_Table1 REFERENCES Table1(Table1ID)
);
And in diagrams:
Table2 is the child of Table1, because Table2 has the foreign key to its parent. (Apologies for the names, but calling the tables Parent and Child would defeat the analysis).
If there are no foreign keys
This can be more difficult. Have a look for evidence such as:
Column naming conventions - often foreign key columns are of the form <TableName>Id - this might help.
Usage - look for other database entities like views, store procedures, rules or functions, and specifically, for how tables are JOINed together - this may be useful in determining the relationship between the tables.
False Positives
In "OO" terms, database parent-child relationships would usually be equivalent to
OO Composition, i.e. the child cannot exist without the parent.
Note however that database foreign keys are also commonly used for:
Non parent-child relationships, such as Classification
e.g.
CREATE TABLE Person
(
...
LocationId INT FOREIGN KEY REFERENCES Country(CountryId)
)
Here, both person AND country could logically exist without each other, so this relationship is more like an OO Aggregate or Association relationship, rather than a parent-child relationship.
Inheritance and extension tables
Both OO inheritance and database table 'extension' patterns are modelled slightly differently to parent-child, as the second table's primary key is also a foreign key to the parent tables' primary key, i.e. a row in Table2 must have a single, corresponding row in Table1, so the cardinality between Table1 to Table2 is 1 to 0..1, whereas parent-child would be 1 to 0..n
CREATE TABLE Table1
(
-- Key for Parent
Table1ID INT CONSTRAINT PK_Table1 PRIMARY KEY,
);
CREATE TABLE Table2
(
-- Table2's primary key is ALSO a FOREIGN key to Table 1
SomeId INT CONSTRAINT PK_Table2 PRIMARY KEY,
CONSTRAINT FK_Table2_Table1 FOREIGN KEY (SomeId) REFERENCES Table1(Table1ID)
);
A dead giveaway for spotting OO relationships in database models is the existence of multiple 'subclass' tables which re-use, AND reference, the base table's primary key.
In table extension (usually a design smell), there will likely be an unusually large number of columns in Table1 which then overflow into Table2 (The Siebel customer tables come to mind).
A parent-child relationship is defined by the presence of a foreign key constraint. The constraint is generally created on the child table, but that's just syntactical -- the constraint really exists as its own entity and is linked to both tables.
The child table would have one or more columns which relate to one or more columns on the parent table. The parent table column(s) must have a primary or unique constraint place on them.

SQL Foreign Key Redundancy

This is a question about foreign key redundancy
redundant foreign key? <- Similar Question
In General:
A Foreign Key from TABLE C references a Primary Key from Table B
A Foreign Key From Table C references a Primary Key from Table A
A Foreign Key from Table B references a Primary Key from Table A
Is the Foreign Key from C -> A necessary since C is connected through B to A?
Specific: 3 tables
Supplier Info Table A
Supplier ID - PK
Person Contact Info (for supplier) Table B
Part # - PK
Date Received - PK
Supplier ID - FK
Part Rprt Table C
Part # - PK & FK
Date - PK & FK
Supplier ID - FK
Thanks - Suggestions for reworking all the table are also welcome
The key would technically be redundant if you assume that the supplier for a person is always the supplier represented by the part. Remember, that things can change over time. Presumably, suppliers could merge, persons could change the supplier they are associated with, and the supplier associated with a part could change.
The data structure, however, does not look properly normalized. I would think that you would want a person table with information only about the person. I don't get the relationship between parts and persons.
So, I think you should rework your data structure. I would suggest that you start with the entities you have identified -- suppliers, persons, and parts. Then create association tables for them, if necessary. It is quite possible that each person should just have a SupplierId and each part should have a SupplierId and that models the relationships. If there is a relationship between parts and persons, then you might be able to satisfy that with just a PersonId field in parts.

Sql modifying relationships

how do you change the relationship between two tables to a many to many to many relationship in sql. Im using oracle for the DB.
thanks
Relationships among tables are almost always, ONE-TO-MANY, or ONE-TO-ONE. There is no MANY-TWO-MANY relationship between two tables. If you want a MANY-TO-MANY you will need to create intermediate relation to hold the relationship.
For example, if you want a MANY-TO-MANY relationship between table A and B you will need to create an intermediate table C:
create table a (a_id number primary key);
create table b (b_id number primary key);
-- c will hold many-to-many relationship between a and b
create table c (
a_id number not null references a(a_id),
b_id number not null references b(b_id),
primary key(a_id, b_id)
);

Designing 1:1 and 1:m relationships in SQL Server

In SQL Server 2008, how does one design a 1:1 and 1:m relationship?
Any relationship requires that the "parent" table (the one side) have a Primary (or unique) Key (PK), that uniquely identifies each row, and the "child" table (the other side) have a Foreign Key column or columns, that must be populated with values that are the same as some existing value[s] of the Primary Key in the parent table. If you want a one to many (1-M) relationship then the Foreign Key should be an ordinary attribute (column or columns) in the child table that can repeat (there can be many rows with the same value)
If you want a one to one (1-1) relationship then the Foreign key should itself be a Primary Key or unique index in the child table that guarantees that there may be at most one row in the child table with that value.
A 1-1 relationship effectively partitions the attributes (columns) in a table into two tables. This is called vertical segmentation. This is often done for sub-classing the table entities, or, for another reason, if the usage patterns on the columns in the table indicate that a few of the columns need to be accessed significantly more often than the rest of the columns. (Say one or two columns will be accessed 1000s of times per second and the other 40 columns will be accessed only once a month). Partitioning the table in this way in effect will optimize the storage pattern for those two different queries.
Sub-Classing. The above actually creates a 1 to zero or one relationship, which is used for what is called a sub-class or subtype relationship. This occurs when you have two different entities that share a great number of attributes, but one of the entities has additional attributes that the other does not need. A good example might be Employees, and SalariedEmployees. The Employee table would have all the attributes that all employees share, and the SalariedEmployee table would exist in a (1-0/1) relationship with Employees, with the additional attributes (Salary, AnnualVacation, etc.) that only Salaried employees need.
If you really want a 1-1 relationship, then you have to add another mechanism to guarantee that the child table will always have one record for each record/row in the parent table. Generally the only way to do this is by enforcing this in the code used to insert data (either in a trigger, stored procedure or code outside the database). This is because if you added referential integrity constraints on two tables that require that rows always be in both, it would not be possible to add a row to either one without violating one of the constraints, and you can't add a row to both tables at the same time.
One-to-One Relationship
Create Table ParentTable
(
PrimaryKeyCol ... not null Primary Key
, ...
)
Create Table ChildTable
(
, ForeignKeyCol ... [not] null [Primary Key, Unique]
, ...
, Constraint FK_ChildTable_ParentTable
Foreign Key ( ForeignKeyCol )
References ParentTable( PrimaryKeyCol )
)
In this case, I can never have more than one row in the ChildTable for a given ParentTable primary key value. Note that even in a One-to-One relationship, one of the tables is the "parent" table. What differentiates a One-to-One relationship from a One-to-Many relationship purely in terms of implementation is whether the ChildTable's foreign key value has a Unique or Primary Key constraint.
One-to-Many Relationship
Create Table ParentTable
(
PrimaryKeyCol ... not null Primary Key
, ...
)
Create Table ChildTable
(
, ForeignKeyCol ... [not] null
, ...
, Constraint FK_ChildTable_ParentTable
Foreign Key ( PrimaryKeyCol )
References ParentTable( PrimaryKeyCol )
)
In this scenario, I can have multiple rows in the ChildTable for a given ParentTable primary key value.
A 1:1 relationship exists where table A and table B only exist once in regards to each other.
Example: A student has 1 master student record. The student would be table A and the record in table B. Table B would contain a foreign key to the student record in table A (and possibly vice-versa)
A 1:m relationship exists where table A can be referenced or linked to by many entries in table B.
Example: A student can take several books out from the library. The student again would be table A and the book could be the entry in table B. The entry in table B would contain a foreign key to who checked the book out, and many books could reference the same student.