The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint - sql

I have created table Employee
Create table Employee
(
FName varchar(20) Not Null,
LName varchar(20) Not Null,
SSN int Not Null,
BDate Datetime,
Address varchar(50),
Sex char(1),
Salary money,
Super_SSN int,
Primary Key(SSN),
Foreign Key(Super_SSN) references Employee(SSN)
)
When i try to insert first row to ,
insert into Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
values('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)
I am getting the error like..
Error:
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Employee_Employee". The conflict occurred in database "Company", table "dbo.Employee", column 'SSN'.

You need to first INSERT record for SSN '33344' with Super_SSN value as NULL.
INSERT INTO Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES (<FName>,<LName>,'33344',<BDate>,<Address>,<Sex>,<Salary>,NULL)
After that insert
INSERT INTO Employee (FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES ('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)
If SSN '33344' have any Super_SSN, update the SSN value (this record should be available in table).

The error is likely thrown because there is a foreign key from Super_SSN to SSN column. You cannot insert a value of 33344 into Super_SSN unless that value already exists in SSN. Try inserting null into Super_SSN or inserting user 33344 first.

Related

Why does the DBMS say that the primary key is not present in the table

I am a CS student that is taking his first course in databases so here I am using Postgresql to create a database with the following tables: employee, project, and worksOn.
So if you run the program you can see that both the employee and project table are created.
However, worksOn is not because it gives me the following error:
SQL Error [23503]: ERROR: insert or update on table "workson" violates foreign key constraint "fk_employee"
Detail: Key (essn)=(222443333) is not present in table "employee"."
I know people won't like it but if you could help that would be highly appreciated. Also, take in consideration that I never dealt with databases and I spent like a week on this.
DROP TABLE IF EXISTS employee;
DROP TABLE IF EXISTS project;
DROP TABLE IF EXISTS worksOn;
create table employee(
Ssn bigint generated always as identity,
Fname varchar(45) not null,
Lname varchar(45) not null,
primary key(Ssn)
);
create table project(
Pname varchar(45) not null,
Plocation varchar(45) not null,
Dnum int not null,
Pnumber int generated always as identity,
primary key(Pnumber)
);
create table if not exists worksOn(
Hours int not null,
Essn bigint,
Pno int,
-- index fk_emplyee,
constraint fk_employee
foreign key(Essn)
references employee(Ssn)
-- constraint fk_project
-- foreign key(Pno)
-- references project(Pnumber)
-- on delete set null
);
insert into employee (Fname, Lname)
values('Jim', 'Brown');
--insert into project (Pname, Plocation, Dnum)
--values('ProjA', 'Boston', 3);
insert into worksOn (Essn, Pno, Hours)
values(222443333, 1, 20);
Your ssn column is defined as a identity column which means it's generated automatically whenever you do not specify a value for it during insert. Given your SQL script the SSN value for Jim Brown will be 1, not 222443333 as you expected.
You need to remove the identity attribute from the column, then provide it during insert into the employee table:
create table employee(
ssn bigint, --<< no identity!
fname varchar(45) not null,
lname varchar(45) not null,
primary key(ssn)
);
....
....
insert into employee (ssn, fname, lname)
values(222443333, 'Jim', 'Brown');
However, if you do want the SSN to be auto generated, you need to access the latest value when you insert into the workson table:
Assuming employee.ssn is still an identity column, you can use this:
insert into employee (fname, lname)
values('Jim', 'Brown');
insert into project (pname, plocation, dnum)
values('ProjA', 'Boston', 3);
insert into workson (essn, pno, hours)
values(
currval(pg_get_serial_sequence('employee', 'ssn')),
currval(pg_get_serial_sequence('project', 'number')), 20
);

Cross Referencing Table Value for Another Value to allow Insert

How do I look at one table and use it to check another table for data integrity?
I have two SQL Tables.
One that is a person table
CREATE TABLE PERSON
(
ID INT IDENTITY(10000,1) NOT NULL,
Firstname VARCHAR(15),
Lastname VARCHAR(25) NOT NULL,
Birthdate DATE,
Gender VARCHAR(1),
CHECK ( GENDER IN ('M', 'F')),
Street VARCHAR(50),
City VARCHAR(15),
State VARCHAR(2),
CHECK (State IN ('FL','GA','PA')),
Zip INT,
Phone VARCHAR(10),
Employee VARCHAR(1),
CHECK ( Employee IN('Y','N')),
Member VARCHAR(1),
CHECK ( Member IN('Y','N')),
CHECK (Member IN ('Y') or Employee IN ('Y')),
CONSTRAINT PERSON_PK PRIMARY KEY (ID));
And Employee Table
CREATE TABLE EMPLOYEE
(
ID INT NOT NULL,
Datehired DATE DEFAULT GETDATE(),
Status VARCHAR(1),
CHECK ( Status IN ('F','C')),
Position VARCHAR(25),
EmpType VARCHAR(25),
CONSTRAINT EMPLOYEE_PK PRIMARY KEY (ID),
CONSTRAINT EMPLOYEE_PERSON_FK FOREIGN KEY (ID) REFERENCES PERSON);
Let's say someone isn't an employee. I can still insert them into the Employee Table.
INSERT INTO EMPLOYEE
(ID, Status, Position, EmpType)
VALUES
('10000','C','Teaching Classes','Instructor');
How Do I prevent this from happening.
One method is to have a redundant key:
alter table person
contraint unq_person_id_employee
unique (id, employee);
Then add a computed column to employee:
alter table employee add employee as ('Y') persisted;
Finally, add the constraint:
alter table employee
add constraint fk_employee_person
foreign key (id, employee) references person(id, employee);
Now, you are guaranteed that only employees are in the Employee table.

Oracle SQL foreign key data not being displayed when selected

I'm trying to do a project with Oracle SQL and for some reason the foreign keys won't work and I can't see why, there's no errors occurring it just won't display the data when I use SELECT, any help would be greatly appreciated, the code below is the one i'm using
CREATE TABLE Customer(
customerName VARCHAR(10) NOT NULL,
street VARCHAR(120) NOT NULL,
customerCity VARCHAR(10) NOT NULL,
PRIMARY KEY (customerName) );
CREATE TABLE Branch(
branchName VARCHAR(10) NOT NULL,
branchCity VARCHAR(10) NOT NULL,
assets INT NOT NULL,
PRIMARY KEY (branchName) );
CREATE TABLE Deposit(
accountNumber INT NOT NULL,
customerName VARCHAR(10),
branchName VARCHAR(10),
balance DECIMAL(6,2) DEFAULT'0',
PRIMARY KEY (accountNumber),
CONSTRAINT Depositbranch
FOREIGN KEY (branchName)
REFERENCES Branch (branchName)
ON DELETE CASCADE,
CONSTRAINT Depositcustomer
FOREIGN KEY (customerName)
REFERENCES Customer (customerName)
ON DELETE CASCADE);
CREATE TABLE Loan(
loanNumber INT NOT NULL,
customerName VARCHAR(10),
branchName VARCHAR(10),
amount DECIMAL(6,2) DEFAULT'0',
PRIMARY KEY (loanNumber),
CONSTRAINT branchNam
FOREIGN KEY (branchName)
REFERENCES Branch (branchName)
ON DELETE CASCADE,
CONSTRAINT customerNam
FOREIGN KEY (customerName)
REFERENCES Customer (customerName)
ON DELETE CASCADE);
The only statement in which you insert into deposit is the following,
INSERT INTO Deposit(accountNumber, balance) VALUES ('1', '100');
where you are only inserting into accountNumber and balance.
The column customerName has no default value, so in this case it will be null.
In fact, if you query all the columns of the table, you have:
SQL> SELECT * FROM deposit;
ACCOUNTNUMBER CUSTOMERNA BRANCHNAME BALANCE
------------- ---------- ---------- ----------
1 100
SQL>

Integrity constraint (JAVAUSER.SYS_C007925) violated - parent key not found

SQL Error
I'm not sure what I did wrong here
Here is the DDL I used to create my tables
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
Create Table Country (CountryAbbreviation char(2) Primary Key,
CountryName varchar(35));
Create Table Employee (EmployeeID Integer Primary Key NOT NULL,
FirstName varchar(20),
LastName varchar(30),
MI char(1),
HomeAddress varchar(30),
Zip char(5),
DateOfBirth date,
HireDate date,
TerminationDate date,
AnnualSalary number(20,2),
LicenseDate date,
StateAbbreviation char(2),
CountryAbbreviation char(2),
Foreign Key (StateAbbreviation) references HomeState,
Foreign Key (CountryAbbreviation) references Country);
Create Table Truck (VinNumber Integer Primary Key,
Make varchar(25),
Model varchar(30),
Year Integer,
PurchasePrice number(20,2),
LicenseNumber varchar(15));
Create Table EmployeeTruck (EmployeeID Integer,
VinNumber Integer,
Primary Key(EmployeeID,VinNumber),
Foreign Key (EmployeeID) references Employee,
Foreign Key (VinNumber) references Truck);
Create Table Accident (AccidentID Integer Primary Key,
DateOfAccident date,
AccidentDescription varchar(200),
AccidentLocation varchar(100),
EmployeeID Integer,
Foreign Key (EmployeeID) references Employee);
and here is the command i used to try and fill in the employee table
insert into employee
values ('1','brian','kim','j','adfasdf',
'1234','24-nov-1993','24-sep-1993','24-sep-1993',
'1234','24-sep-1993','as','as')
but it always gives me the error i put as the title of this question...
In the table "Employee", you say that Foreign Key (StateAbbreviation) references HomeState, and Foreign Key (CountryAbbreviation) references Country). The values you insert into Employee.HomeState and Employee.CountryAbbreviation have to exist in the tables HomeState and Country before you can insert into Employee.
Insert rows into HomeState and Country before you insert into Employee.
You have other problems, too. Here's an example.
Create Table HomeState (StateAbbreviation char(2) Primary Key,
StateName varchar(25));
insert into HomeState values ('AL', 'Alabama');
insert into HomeState values ('AM', 'Alabama');
insert into HomeState values ('AN', 'Alabama');
All those insert statements succeed. They shouldn't. In this case, StateName is also a candidate key.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Let's take this a little further.
Create Table HomeState (
StateAbbreviation char(2) Primary Key,
StateName varchar(25) not null unique
);
Create Table Country (
CountryAbbreviation char(2) Primary Key,
CountryName varchar(35) not null unique
);
insert into HomeState values ('CA', 'California');
insert into Country values ('AF', 'Afghanistan');
insert into Employee (EmployeeID, StateAbbreviation, CountryAbbreviation)
values (-42, 'CA', 'AF');
The state "California, US" makes sense. The state "California, Afghanistan" doesn't.
An employee having no name doesn't make sense. Declare FirstName, LastName, and HireDate not null.
Bet on this: whatever nonsense your database allows will appear. It's just a matter of time.

Foreign Key Not Populating with Primary Key Values

I have searched for an answer but am not finding it. I have 2 tables. Both have an auto-generated PK. The PK from table 2 is an FK in table 1. Since they are both auto-generated I assumed the FK in table 1 would populate with the value that is auto-generated from table 2 but it is not working. The FK in table 1 ends up null. Here is my SQL code for creating table 1:
CREATE TABLE Employee_tbl (
EmployeeID int PRIMARY KEY IDENTITY,
LastName varchar(20) not null,
FirstName varchar(20) not null,
Age varchar(3) not null,
JobID int FOREIGN KEY REFERENCES JobTitle_tbl(JobID),
)
and here is table 2:
create table JobTitle_tbl(
JobID int PRIMARY KEY IDENTITY,
EEO1Classification varchar(50) not null,
Exempt_nonexempt_status varchar(20) not null,
)
I also have some insert statements:
INSERT INTO Employee_tbl
(LastName, FirstName, Age)
Values
('Smith', 'John', '50'),
...
and:
INSERT into JobTitle_tbl (EEO1Classification, Job_title, )
VALUES ('Office/Clerical', 'Accounting Clerk', ),
Why is the FK value showing null when I query table 1?
The foreign keys will not auto-populate, as it doesn't know what foreign key to use. You need to either insert the rows into the JobTitle_tbl table, then select the IDs back out (or use ##identity if using sql server)
select id from JobTitle_tbl where Job_title = ''
Another option would be to update your insert statements to include the primary key, although you'll have to allow identity inserts first.
SET IDENTITY_INSERT JobTitle_tbl ON
into the JobTitle_tbl (id, title) values (1, 'Manager')
SET IDENTITY_INSERT JobTitle_tbl OFF
In either case, you'll need to then update your first insert statements with the ID that you have.
insert into Employee_tbl (LastName, FirstName, JobID) values ('Smith', 'John', 1)