Weak Entity containing a foreign key as a primary key - sql

I have created a table called STUDENT which consists of Unique ID as the PRIMARY KEY along with other related attributes like Name, Addr, Gender etc....
Since I don't want to increase the table size of the STUDENT, I created a weak entity called ACADEMIC RECORDS which stores the previous Academic Records of the student.But in this table i have only created a PRIMARY KEY Unique ID which references the Unique ID of the student. and there is no other attribute in conjunction with Unique ID in the weak entity ACADEMIC RECORD Table.
As I came across the definition OF A WEAK ENTITY which define its primary key as a combination of weak entity's attribute and the owner's table's primary key(in this case STUDENT)
Is my method of creating a foreign key as the only primary key in the table ACADEMIC RECORD correct??
STUDENT Table
**UID** NAME GENDER ADDRESS PHNO.
ACADEMIC RECORD Table
**UID** HighschoolMarks GradSchoolMarks

There's nothing necessarily wrong with having a primary key that's also entirely a foreign key. It's a common way of implementing something like ‘base classes’, where an entity has a row in a base table, and may have a row in one or more extension tables (one to one-or-zero relationship).
I'm not sure it's the most appropriate schema for what you're doing though. If there really is an exactly one-to-one relationship between academic_records and students, it looks like they are part of the same entity to me.
In which case from a normalisation point of view the record columns should be part of the main students table. Maybe there's an efficiency reason to denormalise, but “I don't want to increase the table size” is not normally an adequate reason. Databases can cope with big tables.

I'm not completely clear on what you are asking, but it sounds like you are using the correct method.
Your STUDENT table requires a primary key to provide a unique reference for each row.
Your ACADEMIC_RECORD table also requires a primary key to provide a unique reference for each row.
Each student may have zero or more academic records, and you want to identify the student to which each academic record belongs. You do this by adding a column in the ACADEMIC_RECORD table which contains the id (the primary key) of the student:
STUDENT ACADEMIC_RECORD
id
id <-------> student_id
name high_school_marks
gender grade_school_marks
address
phone_no
Assume you have three students: Alice, Bob and Dave. Alice and Dave have three academic records, and Bob has two. Your tables would look something like this (I've omitted some columns to make things clearer):
STUDENT
id name
1 Alice
2 Bob
3 Dave
ACADEMIC_RECORD
id student_id
1 1
2 1
3 1
4 2
5 2
6 3
7 3
8 3

Related

Record in one table unique to a record in another table

Let me try to make it simple with an example.
I am creating a database with 2 tables, School and Students
School table with 2 columns SchoolID(PK) and Location
Student table with 3 columns StudentID(PK), SchoolID(FK) and Grade
The Student table will have students from all the schools which can be identified by the foreign key SchoolID. The StudentID column will be unique to each student across all schools. Well and good so far.
I need another column in Student table which will be unique only with respect to the foreign key value. Let's call this ID. I need this column to be unique only to each SchoolID. So, If I filter out the students belonging to a particular SchoolID, I shouldn't get 2 students with same ID.
I'm not sure if that's a valid scenario.
Edit:
This is good
This is not
I think there is something wrong with the datamodel. Since you have StudentID as primary key in Student-table, this column will always be unique in this table. But it seems like you are trying to create a Student-School table where you can have the same student connected to multiple schools (but no the same school multiple times for one single student). I think you need at least 3 tables:
Student (Pk StudentID)
School (Pk SchoolId)
StudentSchool
The StudentSchool table will have two FK-columns: StudentID and SchoolID. To protect from the same student beeing mapped to the same school multiple times you could either have the PK include StudentId and SchoolId or create a Unique constraint.

How to establish a many to one relationship between 2 tables for a field

I am building an database schema for a project and I am bit stuck on this issue. I have 2 tables:
USER table:
Id Name Contact_ID
1 Arun 2
2 Barath 3
3 Charan 2
4 Dinesh 1
CONTACT table:
ID Name Phone Mail
1 Mahesh 1234 Mahesh#Yahoo.com
2 Suresh 54321 Sureh#Google.com
3 Jayesh 9876 Jayesh#Bing.com
4 Ganesh 98754 Gahesh#Safari.com
Each of the users in USER will have a contact in CONTACT.
If a user has a single contact then I can use a foreign key relationship on Contact_ID in USER and build the relationship between them.
But what if an user in the USER table has multiple contacts in the CONTACT table? I am not sure how to build the relationship between them.
Eg:
In USER for user Charan there is one contact, contact 2, but what if there is one more, contact 4?
In that case how can I build the many to one relationship?
It looks like you've got it backwards. Your CONTACT table should have a foreign key reference to USER table, rather than USER containing a foreign key reference to CONTACT. For example:
USER table
Id Name
1 Arun
2 Barath
3 Charan
4 Dinesh
CONTACT table
ID Name Phone Mail USER_ID
1 Mahesh 1234 Mahesh#Yahoo.com 1
2 Suresh 54321 Sureh#Google.com 2
3 Jayesh 9876 Jayesh#Bing.com 1
4 Ganesh 98754 Gahesh#Safari.com 3
Of course, I just used fake data for the new USER_ID column. As you can see, USER with Id 1 (Arun) has multiple contacts (IDs 1 and 3) in the CONTACT table.
In the relational model (and ER model) tables represent (business/application) relationships/associations. FKs (foreign keys) are called "relationships" by pseudo-relational (& pseudo-ER) methods.
-- user "id" has name "name" and ...
user(id, name, ...)
-- contact "id" has name "name" and ...
contact(id, name, ...)
-- user "uid" has contact "cid"
user_has_contact(uid, cid)
If user_has_contact is N:1 in uid:cid then you can replace user & user_has_contact by:
-- user "id" has ... AND user "id" has contact "cid"
user(id, name, ..., cid)
If user_has_contact is 1:N in uid:cid then you can replace contact & user_has_contact by:
-- contact "id" has ... AND user "uid" has contact "id"
contact(id, name, ..., uid)
You should use the first design for M:M. (You don't actually have to but then the joined tables exhibit problems that normalization would tell you to solve by having the separate tables.) This is called an association/junction/join/many-to-many/bridge table in methods that call FKs "relationships". But like every table it represents a relationship/association on some values. (And hence also any identified entities.) It also handles M:0-or-1 & 0-or-1:M . The other two designs can do that too using NULL.
Regardless of the cardinality of user_has_contact it is probably a good idea to keep the three separate because it is straightforward. (True ER modeling would give the two entity tables & one association table.) But you should realize that there is no need to join them.
A FK tells the DBMS that values for a list of columns in a table must appear as a CK (candidate key) elsewhere. (In SQL, a FK says they appear as a superkey, ie SQL PK (primary key) or UNIQUE NOT NULL, elsewhere.)
(Methods that call FKs "relationships" do so because FKs are associated with relationships like user_has_contact that have be joined into what becomes the referencing table. Also it is those relationships' cardinalities that are called the FKs' cardinalities. But a FK constraint just states a fact; it isn't a relationship/association.)
You need to find & follow references for information modeling & database design.

Is this a good database design practice?

I got a Person table, each Person can visit several countries. The countries visited by each Person is stored in table CountryVisit
Person:
PersonId,
Name
CountryVisit:
CountryVisitId (primary key)
PersonId (foreign key to 'Person.PersonId')
CountryName
VisitDate
For the CountryVisit Table, my primary key is CountryVisitId which is an identity column. This design will result in that a Person can have only 1 CountryVisit but the CountryVisitId can be 40 for example. Is it a better practice to create another surrogate key column to act as an identity column while the CountryVisitId be a natural key that is unique for each PersonId ?
It is pretty good. I would suggest that you have a separate table for countries, with one row per country. Then the CountryVisits table would have:
CountryVisitId PrimaryKey,
PersonId ForeignKey,
CountryId ForeignKey,
VisitDate
This will ensure that the country name is always spelled correctly and consistently. If you want a list of countries to get started, check out this Wikipedia page. Also note that your definition of country may be different from the standard list of countries (there are actually several out there), so you should use your own auto-incremented primary key, rather than using the country code.
And, you should relax the requirement and remove the unique or primary key on PersonId, CountryId, unless you want to enforce only one visit per country.

Can a primary key be equal to a different column?

I know that a primary key must be unique, but is it okay for a primary key to be equal to a different column in the same table by coincidence?
For instance, I have 2 tables. One table is called person that holds information about a person (ID, email, telephone, address, name). The other table is staff (ID, pID(person ID), salary, position).
In staff the ID column is the primary key and is used to uniquely identify a staff member. The number is from 1 - 100. However, the pID (person ID) may be equal to the ID. For instance the staff ID may be 1 and the pID that it references to may be equal to 1.
Is that okay?
The job of the primary key is to uniquely and reliably identify each row - therefore, it must be unique and NOT NULL - anything else is irrelevant.
If you just happen to have a second column with the exact same values - I'd be wondering why that is the case - but that doesn't in any way affect the primary key negatively.
Primary key of a table must be unique and not null. There are no restrictions on uniquity between tables. It's 100% up to you.
Yes. There's no checking of relationships between different columns in a table.
The restriction you're worried about doesn't even make sense. Suppose you had a table for persons with columns ID, name, and year_of_birth. It wouldn't allow someone who was born in 1975 to have ID = 1975.

SQL Table Design: Multiple foreign key columns or general "fkName" and "fkValue" columns

Given a table (Contacts) which could apply to distinct items in a database (Employers, Churches, Hospitals, Government Groups, etc.) which are stored in different tables, when leveraging this single contacts table in the end I've found there exist two choices for relating a contact back to one particular "item"
One column for each "item" type with a Foreign Key association, this results in a table looking like:
contactID empID churchID hospID govID conFN conLN ...
One column indicating the type of "item" (fkName) and one column for the value corresponding to the item of that type (fkValue). This results in a table looking like:
contactID fkName fkValue conFN conLN ...
The first means that out of the X possible foreign keys, X-1 will be NULL, but I get the advantages of hard-associated foreign keys.
The second means that I can set fkName and fkValue as NOT NULL but I don't get the advantages of DB-supported foreign keys.
Ultimately, is there a "right" answer? Are there other advantages / disadvantages that I haven't thought about (performance, security, growth/expansion)?
The second approach is an anti-pattern.
You need to set up many-to-many relationship tables between each entity (Hospitals, Churches, Employers, Government Groups, etc.) and Contacts.
If you want to make it easier to query for all of the entities a contact is related to, consider creating a view on top of the many-to-many relationship tables.
I think the second option is better as it will allow you to maintain referential integrity of your database using the in-built SQL features (foreign keys), rather than relying on your code to maintain it.
This is the solution that you should be going towards:
type
----------------
typeId name
1 hospital
2 church
contact
-----------------------------------------
contactId firstName LastName typeId (fk)
1 bob is 1
2 your uncle 2
If Bob can be a contact for more than one type, than you will need a junction table.