on what basis relationship between tables are defined - sql-server

I have a question, if two tables in database are from different entities then how we define relationship between them. i mean can we use some foreign key or any thing to define relationship between them. or we have to create a third table

It depends on what kind of relationship you have. If it´s a 1-1 or 1-N then you will only add foreign key column on the respective table. If you need a N-N (aka N-M) you will need a third table.

There is a design principle that states that a table either defines an entity or a relationship but not both. Therefore, use a third table to model the relationship between your two entities -- yes, even if it is 1-1 or 1-N -- noting that the relationship itself may have its own attributes.

Related

How to determine relationship (1:1, 1:n, n:m) between tables when reverse engineering

I have some tables already created in my database and now I need to draw ER diagram for these tables.
Identified the primary key and foreign key between the
tables
Determined pk-fk relationship using the keys
Now I need to identify the cardinality between the tables. How do I
do this?? Please let me know if there is any set of rules which I
need to consider while evaluating 1:1, 1:M and M:M relationships.
Let me take an example of two tables where am struck at:
Table A has a composite key made of pid and identitytype.
Table B has a composite key made of pid and maritalid.
Table A and Table B are associated with each other using pid and pid
is not null in both the tables.
Let me know what could be the relationship type between Table A and Table B whether it is 1:1, 1:M or M:M. Also, please let me know the sequence of steps that you followed in arriving at type of relationship conclusion.
Thanks,
Dex.
Relationships in the entity-relationship model are very different from what you've got in mind. Relationships are not represented by foreign key constraints - that's the old network data model, and it's limited to binary relationships. The entity-relationship model represents n-ary relationships between entity sets in tables, not between tables.
Foreign key constraints restrict the values of a set of columns to be a subset of the values of another set of columns. They are effectively used to enforce entity sets (domains) - for example, to ensure that every person_id column is a subset of the one that represents all known persons in the system. FK constraints are only used during updates - you could delete all FKs from a database and your SELECT queries and JOINs would work exactly as before, further demonstrating that they don't represent relationships.
A relationship is an association among two or more entity sets, each represented by a suitable key. Relationship instances are always recorded in rows of a table. For example:
A 1:1 relationship between a driver's license and a person would be represented by having the license key and person key together as two columns of a table, and both (separately) uniquely constrained. Whether this is in a license table, a person table, or a separate driver's license table is an implementation detail.
A 1:N relationship between cars and their owners would be represented by having the car key and person key together as two columns of a table, and the entity set on the many side uniquely constrained. This is often implemented in the table recording the attributes of the entity on the many side.
The preceding relationships are simple enough that we can denormalize them and don't need to record the relationship in a separate table. For higher relationships, though, we need separate tables:
An M:N relationship between students and subjects would be represented by having the student key and the subject key together as two columns of a table, and the combination of the two uniquely constrained.
An M:N:P relationship between suppliers, products and regions would be represented by having the supplier key, product key and region key together as three columns of a table, and the combination of the three uniquely constrained.
An M:N:1 relationship between regions, products and suppliers (a sole mandate) would be represented by having the region key, product key and supplier key together as three columns of a table, and the combination of region and product keys uniquely constrained.
See the pattern?
Every role/component of a relationship can have a foreign key constraint defined if the characteristic predicate of that entity set (its required attributes) is represented in a different table. That means a single n-ary relationship can require n different FK constraints.
To determine the cardinality of a relationship from an existing table:
Determine the entity sets represented in the table. Not all columns represent entity sets - some represent value sets, meaning the values have meaning themselves as labels or measures.
Determine which combination of entity sets are uniquely constrained together. These are the many sides of the relationship, and we'll give them variables like M, N, P, etc.
Every other entity set is dependent on the previous combination and represented by a 1 in cardinality.
It's not quite that simple. It's possible for a table's key to involve value sets in addition to entity sets. In these cases, we've got a weak entity/identifying relationship/subtyping situation. These are usually (but not always) 1:N relationships in which the child entity's key partially overlaps with the parent entity's key.
For more information, I recommend Peter Chen's paper The Entity-Relationship Model - Toward a Unified View of Data.
You should look at this SO question:
postgresql-describe-table
In reality, without looking at the schema definition, without a contra-positive example, you have no way of knowing if the table is a 1:1, 1:n, or n:m relation if n = m = 1.
You can do a scan, but it is the constraints that determine that relationship.
If you don't have that data, then you can only demonstrate 1:n and n:m with examples, but it cannot be proven that 1:1 is not n:m without the constraint definitions.
A 1:1 relationship will look like this:
PK - PK
this can only by one-to-(zero or one), as both tables can only have unique keys, 1:n and n:m are not allowed. This would have to be constrained by software on some level to ensure the PK = PK for the separate tables, or more usually, if you really want 1:1 the data is stored, normalized, in the same table. Otherwise, you need to ensure key coordination by a transactional insert, or whatnot. Auto-generated keys are not advised.
A 1:n relationship will look like this:
PK - FK
the FK (foreign key) defines it to be constrained to a primary key in another table, but can be in multiplicity.
An n:m relationship will look like this:
PK - FK|FK - PK
where there are three tables. Two normalized tables with primary keys (the PKs) and a joining table with FK relationships defining the mapping n:m between the tables.
Of course, all of this could be constrained by code using the database, and hence, the table constraints are the only reliable definition of the data schema.
Foreign Keys must point to Primary Keys in another table, so you can't have FK:FK relationships, and there really is no PK:PK relationship defined by the database. That has to be constrained by transactional insert via code. The usual convention is to store data that is PK:PK in the same table, per a normalized data format.
Okay, so, to add a comment, directed at tables A and B; all you can say for certain is you have primary keys consisting of pid:identitytype and pid:maritalid, and if that is the case, for the sake of discussion, say identitytype and maritalid are ints, then you have int:int and int:int, and it tells you nothing. if identitytype has overlap with maritalid, then there is no way to reliably tell them apart. If you are only going to match on pid, then you have an N:M relationship as you have pid:N-pid:M different possibilities which would lead to an N:M relationship.

What is the purpose of data modeling cardinality?

I understand what cardinality is, so please don't explain that ;-)
I would like to know, what the purpose of doing cardinality is in data modeling, and why i should care.
Example: In an ER model you make relations and ad the cardinality to the relations.
When am i going to use the cardinality further in the development process? Why should i care about the cardinality?
How, when and where do i use the cardinalities after i finish an ER model for example.
Thanks :-)
Cardinalities tell you something important about table design. A 1:m relationship requires a foreign key column in the child table pointing back to the parent primary key column. A many-to-many relationship means a JOIN table with foreign keys pointing back to the two participants.
How, when and where do i use the cardinalities after i finish an ER model for example.
When physically creating the database, the direction, NULL-ability and number of FKs depends on the cardinalities on both endpoints of the relationship in the ER diagram. It may even "add" or "remove" some tables and keys.
For example:
A "1:N" relationship is represented as a NOT NULL FK from the "N" table to "1" table. You cannot do it in the opposite direction and retain the same meaning.
A "0..1:N" relationship is represented as a NULL-able FK from "N" to "0..1" table.
A "1:1" relationship is represented by two NOT NULL FKs (that are also keys) forming a circular reference1 or by merging two entities into a single physical table.
A "0..1:1" relationship is represented by two FKs, one of which is NULL-able (also under keys).
A "0..1:0..1" relationship is represented by two FKs, both NULL-able and under keys, or by a junction table with specially crafted keys.
An "M:N" relationship requires an additional (so called "junction" or "link") table. A key of that table is a combination of migrated keys from child tables.
Not all cardinalities can be (easily) represented declaratively in the physical database, but fortunately those that can tend to be most useful...
1 Which presents a chicken-and-egg problem when inserting new data, which is typically resolved by deferring constraint checking to the end of the transaction.
Cardinality is a vital piece of information of a relation between two entites. You need them for later models when the actual table architecture is being modelled. Without knowing the relationship cardinality, one cannot model the tables and key restriction between them.
For example, a car must have exactly 4 wheels and those wheels must be attached to exactly one car. Without cardinality, you could have a car with 3, 1, 0, 12, etc... wheels, which moreover could be shared among other cars. Of course, depending on the context, this can make sense, but it usually doesn't.
A data model is a set of constraints; without constraints, anything would be possible. Cardinality is a (special kind of) constraint. In most cultures, a marriage is a relation between exactly two persons. (In some cultures these persons must have different gender.)
The problem with data modelling is that you have to specify the constraints you wish to impose on the data. Some constraints (unique, foreign key) are more important, and less dependent on the problem domain as others ("salary < 100000"). In most cases Cardinality will be somewhere in between crucial and bogus.
If you are creating the data layer of an application and you decided to use an ORM, maybe it's entity framework.
There's a point when you need to create your models and your model maps. At that point you would be able to pull out your ERD, review the cardinality you put on your diagram and create the correct relationships so your data layer shape matched your database shape.

Difference between one-to-one and one-to-many relationship in a database

When having a one-to-one relationship in a database the other table has a foreign key ID (in this example). And in a one-to-many relationship the table contains many foreign keys.
But does the database know whether this is a one-to-one or one-to-many relationship? Are the relationships that I make in an ER-Diagram only to indicate where there should be foreign keys when making the actual tables?
What is the difference between one-to-one and one-to-many relationship in a database?
In a sense, all the relationships we talk about are not known to the database, they are constructs we have invented to better understand how to design the tables.
The big difference in terms of table structure between one-to-one and one-to-many is that in one-to-one it is possible (but not necessary) to have a bidirectional relationship, meaning table A can have a foreign key into table B, and table B can have a foreign key into the associated record in table A. This is not possible with a one-to-many relationship.
One-to-one relationships associate one record in one table with a single record in the other table. One-to-many relationships associate one record in one table with many records in the other table.
To enable one-to-one relationship you need to add unique constraint to foreign key. It is not possible to have two foreign keys for each table as it will be impossible to create records.
Im having trouble understanding what the actual question is.
Your analysis is for the most part correct, in that if you have a 2 tables, and table2 has a foreign key to table one, it could be either a one-to-one or a many-to-one.
Your sentence "And in a one-to-many relationship the table contains many foreign keys."
The table of the 'many' side still contains one column that is a foreign key, its just that more than one row can have the same foreign key value (many rows point to one parent).
Also note that you can put the foreign key on the parent table, to the child, instead of the other way around. In this way, you can prevent one-to-many if you want to do that. Also note that in this way, more than one parent can share a child, which might or might not be what you want.
The database-level equivalent of a 1:1 vs. 1:m is having a unique index on the foreign key column. Note that this will only work for 1:1, NOT 1:0..1, as null is considered when evaluating uniqueness. There are workarounds for this restriction, but that's it at the basic level.
Similarly by example, a product has only one product code, so it's one-to-one relationship (product <-> ABC123), but a customer can purchase more than one product, so it's one-to-many relationship (person <->>>product).
well, you are right, this relation is important for you, but not for db itself. When you have two tables, one with your basic information, and another one with your detailed information.. for both tables you are you, so it is one-to-one relation, you can not map your data to somebody else.
Now add third table "cities" and one of your information points to city you live in - this is example of one-to-many (one city can be used, and should be used for many people).
one-to-many / one-to-one just show how your tables interact. And all the time, you want to "save" rows/columns in table not duplicating them you will use one-to-many relation with another table. Or many-to-many :)
Let's assume you have a table with two attributes A and B. If A is a candidate key and B is not then the relationship between A and B is 1 to many. If both A and B are candidate keys then the relationship is 1 to 1.
Given table A and B if
A and B have a strict 1 to 1 relationship
For every B instance, there will always be an A instance
The best approach is to make the primary key of B also a foreign key referencing A. This is also called "Table per Type Inheritance" and the "is a" relationship. There are other ways to enforce a unique foreign key, but using the primary key makes the relationship clear in the schema and in ER diagrams.
Of course there are always other scenarios, and if your design doesn't meet both of the criteria above, you'll have to use another approach.

Database design - defining a basic many-to-one relationship

This is a basic database design question. I want a table (or multiple tables) defining relationships between customers. I want it so PrimaryCustomer can be linked to multiple SecondaryCustomers, and can have many SecondaryCustomers with the same relationship.
PrimaryCustomerID RelationshipID SecondaryCustomerID
1) If the primary key is {PrimaryCustomerID} then I can only have one linked customer of any kind.
2) If the primary key is {PrimaryCustomerID, RelationshipID}, then I can only have one linked customer for each relationship type.
3) If the primary key is {PrimaryCustomerID, RelationshipID, SecondaryCustomerID}, then I can have whatever I like, but having all columns as the primary key seems completely wrong.
What's the right way to set things up?
A third alternative might be for the key to be (PrimaryCustomerId, SecondaryCustomerId), which would make sense if only one type of relationship is permitted per pair of customers. What keys to implement should be defined by what dependencies you need to represent in the table so that the table accurately represents the reality you are modelling. There's nothing wrong in principle with compound keys or all-key tables.
Number 3 is the right way to go for this data model. Linking tables often have all the columns in a join as all they do is link to other tables.
If a customer can only be linked to one primary customer then you can use a simple recursive relationship in the customer table itself.
CustomerID as PK
PrimaryCustomerID as FK to CustomerID
Nothing wrong with No 3.
If you need to prevent reverse-relationship duplicates, you can use
ALTER TABLE CustomerRelationship
ADD CONSTRAINT chk_id CHECK (PrimaryCustomerId < SecondaryCustomerId);

Is there an answer matrix I can use to decide if I need a foreign key or not?

For example, I have a table that stores classes, and a table that stores class_attributes. class_attributes has a class_attribute_id and a class_id, while classes has a class_id.
I'd guess if a dataset is "a solely child of" or "belongs solely to" or "is solely owned by", then I need a FK to identify the parent. Without class_id in the class_attributes table I could never find out to which class this attribute belongs to.
Maybe there's an helpful answer matrix for this?
Wikipedia is helpful.
In the context of relational
databases, a foreign key is a
referential constraint between two
tables.1 The foreign key identifies
a column or a set of columns in one
(referencing) table that refers to a
column or set of columns in another
(referenced) table. The columns in the
referencing table must be the primary
key or other candidate key in the
referenced table.
(and it goes on into more and more detail)
If you want to enforce the constraint that each row in class_attributes applies to exactly one row of classes, you need a foreign key. If you don't care about enforcing this (ie, you're fine to have attributes for non-existent classes), you don't need an FK.
I don't have an answer matrix, but just for clarification purposes, we're talking about Database Normalization:
http://en.wikipedia.org/wiki/Database_normalization
And to a certain extent Denormalization:
http://en.wikipedia.org/wiki/Denormalization
I would say, it's the other way around. First, you design what kind of objects you need to have. For those will create a table.
Part of this phase is designing the keys, that is the combinations of attributes (columns) that uniquely identify the object. You may or may not add an artificial key or surrogate key for convenience or performance reasons. From these keys, you typically elect one canonical key, the primary key, which you try to use consistently to identify objects in that table (you keep the other keys too, they serve to ensure unicity as a business rule, not so much for identificattion purposes.)
Then, you think what relationships exist between the objects. An object that is 'owned' by another object, or an object that refers to another object needs some way to identify its related object. In the corresponding table (child table) you add columns to make a foreign key to point to the primary key of the referenced table.
This takes care of all one to many relationships.
Sometimes, an object can be related multiple times to another object. For example, an order can be used to order multiple products, but a product can appear on multiple orders as well. For those relationships, you design a separate table (intersection table - in this example, order_items). This table will have a unique key created from two foreign keys: one pointing to the one parent (orders), one to the other parent (products). And again, you add the columns to the intersection table that you need to create those foreign keys.
So in short, you first design keys and foreign keys, only then you start adding columns to implement them.
Don't be concerned with the type of relationship -- it has more to do with the cardinality of the relationship.
If you have a one-to-many relationship, then you'd want to assign a Primary Key to the smaller of the tables, and store it as a Foreign Key in the larger table.
You'd also do it with one-to-one relationships, but some people argue that you should avoid them.
In the case of a many-to-many relationship, you'd want to make a join table, and then have each of the original tables have a foreign key to the join table.

Resources