Access add new rows - sql

I have database and when I try to add new row it gives error of Referential Integrity. It says the data can not be added because of referential integrity constraint and foreign key data should be in primary key table. Problem is when I try to add data in Branch table it requires managerNo and in Manager table it requires technicianNo and in Technician table it requires customerNo.

So,
Let's start with the Branch table.
[Branch]
brandID,
buildingnumber
streetname
city
postcode
phone
fax
[Branch_Technicians]
branchID
technicianID
[Technician]
technicianID
name
housenumber
streetname
city
postcode
phonenumber
So initially, your relationship was ONE BRANCH CAN HAVE MANY TECHNICIANS which is correct, however, what you've got to understand is that ONE TECHNICIAN CAN WORK AT MANY BRANCHES, therefore creating a many to many relationship, to resolve this I have created an extra table called Branch_Technicians this is called an Associative Entity.
I won't complete all of it, I'll let you work out the rest, as I do not have the time to construct an entire database. I could go into greater depth. But this is how I'd do it.. work with this (that's what I'd recommend)
Hope this helps,
Sohail.

Related

get confused in primary key concept and nomalisation

Let's take an example of a login table with the columns: id (primary key),username,password,status.
id is primary key but still we authenticate user by searching table through username+password. Doesn't it violate normalisation rule?
Another example: suppose we have two tables, employer and job
employer table's id is used injob table as foreign key but job table itself has its own id
job table
---------
id (primary key) || employer_id (foreign key) || etc etc
Now when we will search job posted by a employer we use employer_id but this table has its primary key?
Primary key on any table is an unique identifier and indexed by default. It does not mean that records will always be searched through that field itself. Now, when you are to link a parent record to a child record, you can use the primary key to establish the relationships.
While trying to get the records, you will make use of primary key as a link between different tables. For example, you have employers and employees. A search might look like: "Get me all the employees for this employer". Now, employer is the main entity here and we are looking for linked employee records for it. Here, employer id will help us fetch related records. A query for the same might appear something like this:
SELECT [COLUMN NAMES HERE]
FROM EMPLOYER INNER JOIN EMPLOYEE ON
EMPLOYER.ID = EMPLOYEE.EMPLOYERID
I suggest you to read some tutorial, but, shortly ... a primary key is an id that is unique and not null and identifies an entry in your table. A foreign key is a reference to an id in another table. As you said, employee and job tables. An id is in most cases generated by a sequence, you don't know its value before inserting the record.
You usually perform seraches through username, name, ... datas that are user-known. In your case, when you search for a job, you will probably perform a Join. A join is a relation (and there are more types) between tables. In your case you will do
select *
from employer emp inner join job jjj on emp.id = jjj.employer _id
The ids are usefull, code-wise, when you have to update/delete a record. In this case usually you know everything about your record, id included, then you will use the id (also because ids usually have indexes, so the queries are faster). You can usually create indexes in the columns you use in filters, in order to reduce the execution time of your queries.
We need to distinguish between business (or candidate) keys and technical (or surrogate) keys. The business key is the data item(s) which uniquely identify this row in the real world. The technical key is a convenience for data management, generated by some computer process such as a sequence or sys_guid().
Yes, the use of technical keys means storing redundant information but this is a case where practicality trumps theory. Primary keys should not change but in real life they can (e.g. people change their name due to various life events). Technical keys have no meaning so do not change. Business keys are often compound keys, which is often inconvenient for enforcing foreign keys (and occasionally highly undesirable, for instance when the business key is a sensitive data item such as Social Security Number).
So, it is common for tables to have an ID column as the primary key, which is used for foreign key relationships, and a unique constraint to enforce the business key.
In your first example username is a business key and id is a technical key. This is one reason why we should have two data models. The Logical Data Model has an Entity called user with a candidate key of username. The physical data model has a Table called user with a primary key of id and a unique key of username.
For your second example, it seems you're modelling a Situations Vacant job board. The relationship between Employer and Job is one to many, that is an employer can advertise many jobs. So the Job table has its own primary key, id, plus a foreign key employer_id which references the primary key of the Employer table. This means we can find all the jobs for a specific employer. But because the job table has its own primary key we can identify each job so that we can distinguish the Janitor job at Harrisons Pharmaceuticals from the Janitor job at Ravi's Cash'n'Carry. (Which incidentally shows why we need technical keys: imagine if the employer_id foreign key was a string of varchar2(128) for each row on the Job table. )
In a Logical Data Model the employer_id would be implied on the Entity job by a link to the Entity employee but would be shown (actually it might, it depends on the tool). In the physical model the column must be added to the dependent table, because database constraints (and joins!) physically need the column in order to work.
So we can see that Normalisation applies to the representation and storage of business data but the practicalities of database engines mean that we need additional columns to manage the data.

Design conditional relationship

I need help with designing my database tables.
Employee
Id
EmployeeTypeId
EmployeeType
Id
Name
Car
Id
EmployeeId
How do I enforce that only one type of employee (driver) can be a foreign key in the Car table or should I redesign the tables?
I consider it a good idea to forearm the database such that implausible data cannot be entered. To enforce this here, however, is a bit tricky...
Solution 1:
Add EmployeeTypeId to the Car table. Then make (EmployeeId, EmployeeTypeId) a foreign key to the Employee table (where you might have to create a uniqe constraint on the two fields, in order to be able to use them for a foreign key reference). Then add a constraint on Car.EmployeeTypeId to ensure it's a driver. I know this looks redundant, but it really is no problem, because you cannot assign an Employee another EmployeeType here, so consistency is still guaranteed. I admit this approach is a bit clumsy, though.
Solution 2:
Use a before-insert tigger on the Car table, look up the employee and make sure it is a driver, else throw an exception. This is a better solution in my opinion, alone for its simplicity. You could then add a column to table Car holding a unique name for the types that you use, e.g. UniqueName = 'DRIVER', so you don't have to use the ID as a magic number. You see, normally one EmployeeType is a s good as the other in a database. If you want to build special logic on a certain entry, you need a handle for this. The unique name is one way to do this, a flag IsDriver = TRUE/FALSE would be another.

How do I create a table model in SQL?

Let's say I've 3 tables: enterprise, users, houses.
Everyone needs an address. What should I do?
Create a table address for everyone?
Create one unique table address?
Assuming that the first is "more" correct (cache, fragmentation, size, ...), how should I write it in plain SQL?
How do I create a "model" of the table address, and use it in custom tables (e.g. enterprise_address)?
* So when I change one field in the model, it gets replicated.
It appears you need every user to have an address. You have multiple ways to solve it.
Handle it in UI
Your users table will be just information about users (on address info here)
Create addresses table with addressid as primary key
Create many-to-many table/junction table called user_addresses that brings userid and addressid together
Ensure that your UI mandates address for each user
Tables
create table addresses (addressid int not null PK, line1, line2, city ...);
create table users (userid int not null PK, username, ...);
create table user_addresses (user_addressid int, userid int, addressid int, UK userid + addressid, FK to users, FK to addresses);
This allows a user to have multiple addresses. You have the flexibility of marking which one is primary.
Handle it in DB (and UI)
create table addresses (addressid int not null PK, ....);
create table users (userid int not null PK, username varchar(20), ..., addressid int not null, FK to addresses);
This allows one address per user.
and handle it also on the UI to ensure that address is supplied. Enter address into addresses first and then into users (make it an atomic process; use transactions!)
You can start with one these methods and analyze what your business needs are. Work with your DBA, if you have one, to see what their experience says about the business and previous DB designs similar to this.
Just from the three given tables I would assume that address is something you would want to put in either Houses or Users.
Depending on how much detail you want to keep track of in the Address it could be work making a separate table but there are a number of ways to go about this and the correct method depends solely on what you are trying to achieve.
Without knowing any of the required information all I can really advise is that you should aim to store the addresses as unique values. Once you have this you can assign each address to any other table you wish using a Foreign Key.
If you want to store multiple fields for the address then you will require a seperate table, if a single field will do then it could just as easily be added to the person or houses table.
One thing that would make a major difference to which way you would want to do this is the relationship between address and your other entities. For example if a user can have many addresses then you cant make it a part of the user table, and if an address can have multiple users assigned to it then it cant use a FK to represent its relationship to the users table.
One way you can do this is to make a relational table. So you make addresses and users seperate tables then have another table with just an id(pk) and 2 fks linking it to each of the other tables. This way you can have a many to many relationship if you wish.
First question: how many addresses per enterprise/user/house? If there are multiple addresses per entity, that leads you to want a separate address table, possibly with an address type.
Examples of multiple address situations:
Multiple locations
Ship-to addresses
Physical vs. PO Box
If you are going to assert that an entity can only have one address, then you probably prefer making the address part of the entity row, for simplicity. However, there can be reasons not to do that; for example, table width (number of columns in the table).
If you have multiple addresses per entity, typically you will use a foreign key. The entity should have an abstract key: some kind of ID. This will either be an integer or, in SQL Server, it could be a uniqueidentifier. The entity ID will be part of the key for the address.
Ok, I found the answer to postgresql: use INHERITS
e.g. CREATE TABLE name () INHERITS (table_model)
Thank you all for the answers.

Converting an ER diagram to relational model

I know how to convert an entity set, relationship, etc. into the relational model but what i wonder is that what should we do when an entire diagram is given? How do we convert it? Do we create a separate table for each relationship, and for each entity set? For example, if we are given the following ER diagram:
My solution to this is like the following:
//this part includes the purchaser relationship and policies entity set
CREATE TABLE Policies (
policyid INTEGER,
cost REAL,
ssn CHAR(11) NOT NULL,
PRIMARY KEY (policyid).
FOREIGN KEY (ssn) REFERENCES Employees,
ON DELETE CASCADE)
//this part includes the dependents weak entity set and beneficiary relationship
CREATE TABLE Dependents (
pname CHAR(20),
age INTEGER,
policyid INTEGER,
PRIMARY KEY (pname, policyid).
FOREIGN KEY (policyid) REFERENCES Policies,
ON DELETE CASCADE)
//This part includes Employees entity set
CREATE TABLE Employees(
ssn Char(11),
name char (20),
lot INTEGER,
PRIMARY KEY (ssn) )
My questions are:
1)Is my conversion true?
2)What are the steps for converting a complete diagram into relational model.
Here are the steps that i follow, is it true?
-I first look whether there are any weak entities or key constraints. If there
are one of them, then i create a single table for this entity set and the related
relationship. (Dependents with beneficiary, and policies with purchaser in my case)
-I create a separate table for the entity sets, which do not have any participation
or key constraints. (Employees in my case)
-If there are relationships with no constraints, I create separate table for them.
-So, in conclusion, every relationship and entity set in the diagram are included
in a table.
If my steps are not true or there is something i am missing, please can you write the steps for conversion? Also, what do we do if there is only participation constraint for a relationship, but no key constraint? Do we again create a single table for the related entity set and relationship?
I appreciate any help, i am new to databases and trying to learn this conversion.
Thank you
Hi #bigO I think it is safe to say that your conversion is true and the steps that you have followed are correct. However from an implementation point of view, there may be room for improvement. What you have implemented is more of a logical model than a physical model
It is common practice to add a Surrogate Instance Identifier to a physical table, this is a general requirement for most persistence engines, and as pointed out by #Pieter Geerkens, aids database efficiency. The value of the instance id for example EmployeeId (INT) would be automatically generated by the database on insert. This would also help with the issue that #Pieter Geerkens has pointed out with the SSN. Add the Id as the first column of all your tables, I follow a convention of tablenameId. Make your current primary keys into secondary keys ( the natural key).
Adding the Ids then makes it necessary to implement a DependentPolicy intersection table
DependentPolicyId, (PK)
PolicyId,
DependentId
You may then need to consider as to what is natural key of the Dependent table.
I notice that you have age as an attribute, you should consider whether this the age at the time the policy is created or the actual age of the dependent, I which case you should be using date of birth.
Other ornamentations you could consider are creation and modified dates.
I also generally favor using the singular for a table ie Employee not Employees.
Welcome to the world of data modeling and design.

Error from SQL Server

Hello friends I am getting the following error while making the foreign key
'tbl_course' table saved successfully
'tbl_students' table
- Unable to create relationship 'FK_tbl_students_tbl_course'.
Introducing FOREIGN KEY constraint
'FK_tbl_students_tbl_course' on table
'tbl_students' may cause cycles or
multiple cascade paths. Specify ON
DELETE NO ACTION or ON UPDATE NO
ACTION, or modify other FOREIGN KEY
constraints. Could not create
constraint. See previous errors.
I have the following tables College table, Branch table, Course table and Student table
Course has a foreign key college_id, Branch has a foreign key course_id and I want to make college_id, course_id, branch_id as foreign keys to my Student table but while making course_id and branch_id as foreign key in Student table it generate the error mentioned above...please help me to resolve the above problem.....thanks
According to MS
You receive this error message because in SQL Server, a table cannot appear more than one time in a list of all the cascading referential actions that are started by either a DELETE or an UPDATE statement. For example, the tree of cascading referential actions must only have one path to a particular table on the cascading referential actions tree.
http://support.microsoft.com/kb/321843
Can you live without the cascading deletes? Keep the referential ingegrity but not the referenctial actions (cascades). You could resort to a trigger as a work around if needed.
EDIT:
CREATE TRIGGER [dbo].[tr_College_Delete] ON [dbo].[College]
FOR DELETE
AS
BEGIN
DELETE FROM student
where collegeid in (select collegeid from deleted)
END
not tested.
Why would you add anything but branch_id to the student? From there, you should be able to determine which course the branch belongs to and which college the course belongs to.
If you have
College
College1
College2
College3
Course
Course1, College1
Course2, College1
Course3, College2
Branch
Branch1, Course1
Branch2, Course1
Branch3, Course2
Student
Student1,College3,Course3,Branch1
This is valid from the database standpoint, but makes no sense since the student record should be attached to College1 based on the Branch it's attached to. You know logically that if the student is in a branch with ID Branch1 (or whatever primary key you use, but I use this for illustraion purposes) then they must be in Course1 and College1. By adding the additional information to the Student record, you not only create circular references in the code but put yourself in a position to create a "corrupt" record in the database. Of course you can code around this, but why go to the extra effort when you can simplify the student record to simply (Student1,Branch1) without losing any data?
This is known as database normalization, and it's something that's very important to at least consider when you're building a data model.