How to create tables in SQL when they reference each other in SQL server. Furthermore how to ensure no errors pop up during data insertion - sql

I have two tables Employee and Customer Account. The employee advises the customer account:
Here is the SQL I have written for the Employee Table. (Don't mind the Person(PersonID), it works, since the Person has no foreign keys. But the Customer(SSN) reference suffers from this issue as well.):
CREATE TABLE Employee(
SSN Varchar(50) NOT NULL PRIMARY KEY,
Manages Varchar(50),
PersonID varchar(50) FOREIGN KEY REFERENCES Person(PersonID ),
Advises varchar(50) FOREIGN KEY REFERENCES CustomerAccount(AccountNo),
);
And here is the SQL for the Customer Account Table:
CREATE TABLE CustomerAccount(
AccountNo Varchar(50) NOT NULL PRIMARY KEY,
AdvisiorID VARCHAR(50) FOREIGN KEY REFERENCES Employee(SSN),
OwnerSSN Varchar(50) FOREIGN KEY REFERENCES Customer(SSN),
);
As we can see I can't create either CustomerAccount or Employee since both of them depend on each other. How should I resolve this issue?
Also when inserting using insert statements, it would probably give errors entering data, How should I resolve that?

Related

SQL Foreign key error --Missing index for FK constraint

CREATE DATABASE Company;
USE Company;
CREATE TABLE Employee(
EmployeeID INT PRIMARY KEY,
EmployeeName CHAR(25),
DID INT NOT NULL
);
CREATE TABLE Department(
DepartmentID INT NOT NULL,
DpartmentName CHAR(25),
FOREIGN KEY (DepartmentID) REFERENCES Employee(DID)
);
This is a simple SQL query for creating 2 tables and adding a foreign key,
I made sure to--
Have same data type
Different names in table.
Correct syntax.
But still, I get the error for
0 23 16:48:05 CREATE TABLE Department(
DepartmentID INT NOT NULL,
DpartmentName CHAR(25),
FOREIGN KEY (DepartmentID) REFERENCES Employee(DID)
) Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'department_ibfk_1' in the referenced table 'employee' 0.329 sec
How do I correct this? Thanks in advance
Missing index for constraint 'department_ibfk_1' in the referenced table 'employee'
You need an index on the DID column of the Employee table if you are creating a foreign key referencing the Employee.DID column.
But as suggested in the comments, you likely want it the other way around: the Employee.DID column sounds like a reference to Department.Id.
Thus, the foreign key should be on the Employee table, referencing the Department table. (And this way, there wouldn't be any error as Department.id is already indexed).

Create 2 tables having same column but not a primary key

( Question is only for a college project as I'm stuck with the requirement)
I want to create 2 tables in SQL Server, say 'table1' and 'table2' in the same database. Both should have a column say 'col1' which is not a primary key.
So how should I create it so that when I insert data into one table, the other gets updated automatically?
NOTE: So this is for a college project, we are asked to make a specific type of primary keys so referencing that is not an option, now I have to have same entity in 2 different tables, so is a good idea to somehow reference them, any ideas?
For eg, en employee's project details will have his/her empID and the dependants' table will have empID as well. But I cannot make it primary key since that is already defined by the Professor. But updating one should update another as well, does that make sense?
You can have two types of parent-child relationship.
Identifying relationship : Here, child depends on the parent to identify itself. E.g. Project requires Employee to exist. Here, Project should have EmployeeId part of its primary key or EmployeeId as its primary key. If EmployeeId is primary key of project then, an employee can have only one project.
CREATE TABLE Employee
(
EmployeeId INT,
EmployeeName VARCHAR(255) NOT NULL,
PRIMARY KEY(EmployeeId)
)
GO
CREATE TABLE EmployeeProject
(
EmployeeId INT,
EmployeeName VARCHAR(255) NOT NULL,
PRIMARY KEY(EmployeeId),
FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId),
)
GO
Non-identifying relationship: Here, child does not depend on the parent to identify itself. E.g. Project can be defined without Employee. Here, Project can have EmployeeId as foreign key. If EmployeeId is NOT NULL column, then it is mandatory to have an employee. If EmployeeId is NULL column, then it is not mandatory to have an employee.
CREATE TABLE Employee
(
EmployeeId INT,
EmployeeName VARCHAR(255) NOT NULL,
PRIMARY KEY(EmployeeId)
)
GO
CREATE TABLE EmployeeProject
(
EmployeeProjectId INT,
EmployeeName VARCHAR(255) NOT NULL,
EmployeeId INT NOT NULL, -- Can be NULL, if it is not mandatory
PRIMARY KEY(EmployeeProjectId),
FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId),
)
GO
First while creating tables, the entity which is to be refereced as foreign key, make it unique:
Table1:
[SIN] int NOT NULL UNIQUE,
Second, in another table where calling [SIN] as FK, put conditions for update and delete:
Table2:
[SIN] INT CONSTRAINT [SIN_FK1] FOREIGN KEY REFERENCES Employee([SIN]) ON DELETE SET NULL ON UPDATE CASCADE
By doing this, whenever you update or delete records in Table1, the corresponding record in Table2 will be updated.

Missing Keyword in SQL Code on Foreign Keys unable to create the table

Trying to create a table with an SQL code, but I'm getting an error:
Missing keyword
in regards to the foreign key.
CREATE TABLE Staff
(
staffID VARCHAR(5) NOT NULL,
name VARCHAR(50),
position VARCHAR(30),
branchID VARCHAR(5),
PRIMARY KEY (staffID),
FOREIGN KEY (branchID) REFERENCES Branch ON UPDATE CASCADE
);
Unlike other RDBMS (such as MySQL for example), Oracle does not support the ON UPDATE clause in foreign keys. You would just need to remove that part of the declaration.
Try:
CREATE TABLE Staff (
staffID VARCHAR(5) NOT NULL,
name VARCHAR(50),
position VARCHAR(30),
branchID VARCHAR(5),
PRIMARY KEY (staffID),
FOREIGN KEY (branchID) REFERENCES Branch(branchID) --ON UPDATE CASCADE
);
Demo on DB Fiddle
The logic behind this Oracle behavior is that the referred column is not supposed to change, since it must be PRIMARY KEY (or a UNIQUE column). I believe that this limitation makes sense... they just don't want to give users enough rope to hang themselves with.

Are these FKs necessary -- and are they stopping me?

I'm having some difficulties with a database I'm creating for a summer camp, specifically with the PK and FK constraints. When I declare the FK constraint (e.g. FOREIGN KEY(PID) references Campers(CamperID)) I get an error running my code through pgAdmin (I'm using PostgreSQL). I understand that, for example, the Campers table is not yet created, and this is most likely part/all of the roadblock, however I feel like my FKs are still wrong somehow. To my understanding, a FK is a PK in another table -- but I feel like there is some redundancy or disconnect between my tables.
I've put the syntax for some of my CREATE statements below. I'm not sure if I'll get reprimanded for the quality of my (somewhat vague) question, but I feel a bit lost and would appreciate any help or advice. Thank you in advance!
DROP TABLE IF EXISTS People;
CREATE TABLE People (
PID VARCHAR(10) NOT NULL UNIQUE,
FName TEXT NOT NULL,
LName TEXT NOT NULL,
DOB DATE NOT NULL,
ArrivalDate DATE NOT NULL DEFAULT CURRENT_DATE,
DepartureDate DATE,
US_PhoneNum VARCHAR(11) NOT NULL,
StreetAddress VARCHAR(200) NOT NULL,
Sex GENDER NOT NULL,
ZIP VARCHAR(10) NOT NULL,
PRIMARY KEY(PID),
FOREIGN KEY(PID) REFERENCES Campers(CamperID),
FOREIGN KEY(PID) REFERENCES Counselors(CounselorID),
FOREIGN KEY(ZIP) REFERENCES Zip(ZIP)
);
DROP TABLE IF EXISTS Zip;
CREATE TABLE Zip (
ZIP VARCHAR(10) NOT NULL,
City TEXT NOT NULL,
State VARCHAR(2) NOT NULL,
PRIMARY KEY(ZIP)
);
DROP TABLE IF EXISTS Campers;
CREATE TABLE Campers (
CamperID VARCHAR(10) NOT NULL REFERENCES People(PID),
AgeGroup AGES NOT NULL,
CabinID VARCHAR(2) NOT NULL,
Bed BEDTYPES NOT NULL,
GroupID VARCHAR(3) NOT NULL,
PRIMARY KEY(CamperID),
FOREIGN KEY(CamperID) REFERENCES People(PID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID),
FOREIGN KEY(Bed) REFERENCES Beds(Bed),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID)
);
DROP TABLE IF EXISTS Counselors;
CREATE TABLE Counselors (
CounselorID VARCHAR(10) NOT NULL REFERENCES People(PID),
GroupID VARCHAR(3) NOT NULL,
CabinID VARCHAR(2) NOT NULL,
PRIMARY KEY(CounselorID),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID)
);
ERROR message for further clarification:
ERROR: relation "campers" does not exist
********** Error **********
ERROR: relation "campers" does not exist
SQL state: 42P01
There are more tables (obviously) which I can provide the create statements for, if needed.
You should really start here: Foreign key.
In the context of relational databases, a foreign key is a field (or
collection of fields) in one table that uniquely identifies a row of
another table.
What you are trying to do in your script is to create a circular link between People, Campers and Counselors. Having a Primary Key field also a Foreign Key mandates that IDs across all referenced tables are identical.
... and to create a Foreign Key the referenced table must already exist in the database. So you should start with the table that does not have any Foreign Keys and create tables that reference only those tables created previously. Alternatively you can create all tables without Foreign Keys and add them later, when all the tables are present.
... and to answer the question, Foreign Keys are never necessary, but they might help.

SQL Management Studio 2012 Foreign Key Is A Mess

I am trying to add a foreign key to a table. I have created two tables.
CREATE TABLE madeupbusiness.staff
(
staffnum int NOT NULL,
forename varchar(30) NOT NULL,
surname varchar(30) NOT NULL,
meeting int NOT NULL,
PRIMARY KEY (staffnum),
)
GO
meeting should use the PK from from the meeting table to create a FK :
CREATE TABLE madeupbusiness.meeting
(
meetingnum int NOT NULL,
room varchar(30) NOT NULL,
PRIMARY KEY (meetingnum),
)
GO
To create the foreign key I run this query
ALTER TABLE madeupbusiness.staff
WITH CHECK
ADD CONSTRAINT FK_staff_meetingnum FOREIGN KEY (meetingnum)
REFERENCES madeupbusiness.meeting(meetingnum)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO
The query runs but when I create a database diagram there is a square loop the staff table from the staffnum key back onto it. Sorry but I don't really know how to describe it. There is no relationship between the two tables. What am I doing wrong?
I have tried to add the relationship from design view but the foreign key table is greyed out.
If you can rebuild the Table do this:
CREATE TABLE madeupbusiness.meeting
(meetingnum int NOT NULL PRIMARY KEY REFERENCES madeupbusiness.meeting(YourColumnYouWantItShouldBeReferenced),
room varchar(30) NOT NULL);
GO