Trouble with composite foreign keys in sqlite3 - sql

there! I have a failing foreign key constraint in sqlite3 and I really have no idea why. I'm using a composite foreign key as discribed here (http://www.sqlite.org/foreignkeys.html#fk_composite) and a "normal" foreign key.
Here are my schemas:
sqlite> .schema sources
CREATE TABLE sources(
source_id VARCHAR(16) NOT NULL,
source_type INTEGER NOT NULL,
title VARCHAR(128) NOT NULL,
year INTEGER,
month INTEGER,
PRIMARY KEY(source_id),
UNIQUE(title)
);
sqlite> .schema author_aliases
CREATE TABLE author_aliases(
author_id INTEGER NOT NULL,
alias_id INTEGER NOT NULL,
forenames VARCHAR(128),
surname VARCHAR(128) NOT NULL,
PRIMARY KEY(author_id, alias_id),
FOREIGN KEY(author_id) REFERENCES authors(author_id),
UNIQUE(forenames, surname)
);
sqlite> .schema alias_source_relations
CREATE TABLE alias_source_relations(
source_id VARCHAR(16) NOT NULL,
author_id INTEGER NOT NULL,
alias_id INTEGER NOT NULL,
PRIMARY KEY(source_id, author_id, alias_id),
FOREIGN KEY(source_id) REFERENCES sources(source_id),
FOREIGN KEY(author_id, alias_id) REFERENCES author_aliases(author_id, alias_id)
);
Here is the data the foreign key is referring to:
sqlite> SELECT * FROM sources WHERE source_id='Allen1980';
Allen1980|0|The definition of electronegativity and the chemistry of the noble gases|1980|
sqlite> SELECT * FROM author_aliases WHERE author_id=1 and alias_id=1;
1|1|Leland C.|Allen
sqlite> SELECT * FROM authors WHERE author_id=1;
1|Leland Cullen|Allen
And here is my insert:
sqlite> INSERT INTO alias_source_relations VALUES(1, 1, 'Allen1980');
Error: foreign key constraint failed
Does anyone know what I am missing? Thanks for your help!
Regards,
Marian

Check column order!
INSERT INTO alias_source_relations VALUES('Allen1980', 1, 1);

The order of the inserted values does not match the column order as defined in the table schema.
It's safer and also more descriptive to include the column names. Like this, the order does not need to match the one in the table schema and someone who does not know the table schema by heart still understands the command:
INSERT INTO alias_source_relations (source_id, author_id, alias_id)
VALUES ('Allen1980', 1, 1);

Related

SQL Constraint names

If we have query for creating table like this..
create table if not exists food
(
id int not null auto_increment,
user_id int,
name varchar(30),
constraint pk_food primary key(id,name),
foreign key(user_id) references userss(id)
);
What does pk_food mean in this example? I know this is a constraint name, but for what we should be give a name for constraint, if its working without?
create table if not exists food
(
id int not null auto_increment,
user_id int,
name varchar(30),
primary key (id, name),
foreign key (user_id) references userss(id)
);
I mean.. how to use these names and for what we need it?
You gives constraints names for basically two reasons:
You can better understand the error message when the constraint is violated.
You can more easily find the constraint if you want to delete it.

How to define a foreign key

my two parents table are person and artwork. I created their table as follows:
create table person (
person_id number(20) primary key,
name varchar2(20),
address varchar(50),
contact_number number (10)
);
and other
create table artwork (
artwork_id number primary key,
barcode char (20),
title varchar2(20),
description varchar2(50));
When I try to make the child table vote it is giving this error.
create table vote
(
vote_id number(7) NOT NULL,
artwork_id number(20),
person_id number(20),
PRIMARY KEY (vote_id),
FOREIGN KEY (artwork_id) REFERENCES artwork(artwork_id),
FOREIGN KEY ( person_id) REFERENCES Person(person_id)
);
SP2-0734: unknown command beginning "FOREIGN KE..." - rest of line ignored.
You forgot to mention constraint before foreign key:
create table vote
(
vote_id number(7) NOT NULL,
artwork_id number(20),
person_id number(20),
PRIMARY KEY (vote_id),
CONSTRAINT fk_artwork_id FOREIGN KEY (artwork_id) REFERENCES artwork(artwork_id),
CONSTRAINT fk_person_id FOREIGN KEY ( person_id) REFERENCES Person(person_id)
);
Syntax
The syntax for creating a foreign key using a CREATE TABLE statement
is:
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
Demo
http://sqlfiddle.com/#!4/3d141
Explanation
By default SQLPlus doesn't like blank lines. However we can easily configure our SQLPlus environment to ignore them:
SQL> set sqlblanklines on
We can also put the setting in our glogin.sql file (assuming we're allowed to edit it, which isn't always the case).
remove that blank line before the definition of your constraints when creating the vote table:
create table vote
(
vote_id number(7) NOT NULL,
artwork_id number(20),
person_id number(20),
PRIMARY KEY (vote_id),
FOREIGN KEY (artwork_id) REFERENCES artwork(artwork_id),
FOREIGN KEY ( person_id) REFERENCES Person(person_id)
);
Any blank rows will stop SQL*Plus from accepting input lines.
If you want it to avoid this run:
set sqlblanklines on
before any other instruction.

Foreign key in the first table

I have a question about foreign keys.
How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?
CREATE TABLE table1
(
name_id INT NOT NULL,
team TEXT REFERENCES table2(team_id),
PRIMARY KEY(name_id)
);
CREATE TABLE table2
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
If I try the code above I get the following error:
ERROR: relation "" does not exist
Thanks in advance.
Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:
alter table table1 add constraint fk_table1_team
foreign key (team_id) REFERENCES table2(team_id);
The declaration for table1 would be:
CREATE TABLE table1 (
name_id INT NOT NULL,
team_id INT,
PRIMARY KEY(name_id)
);
The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.
here's the syntax of creating a table with Foreign key:
CREATE TABLE table11
(
name_id INT NOT NULL,
team INT,
PRIMARY KEY(name_id),
foreign key(team) references table22(team_id)
);
CREATE TABLE table22
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
but there was another problem. a foreign key from a child table cannot reference to a primary key from a parent folder if they do not contain the same type. in your code team was of TEXT and team_id was of INT which cannot be.

SQL Constraints Confusion

I'm in a bit of a mix right now, I have a Table called Avatars, which has a foreign key called Family. Now, in the family table, I have two Foreign Keys called Mother and Father - Now this is the confusing bit, in both the Mother and Father Tables, there is a Foreign key called Avatar_ID which is of course the Primary Key to the Avatars table. I'm not sure if that's even allowed in SQL PLUS.
Whenever I try and enter the tables 'Family, Mother or Father', I keep getting the error:ORA-02291: integrity constraint (SG304.FK_FATHER_ID) violated - parent key not found.
Is there any way around this? Or will I have to change my code completely? A sample of the code is below.
CREATE TABLE Avatars (
Avatar_ID VARCHAR(10) NOT NULL,
Avatar_Name VARCHAR(30),
AvA_DOB DATE,
Age VARCHAR(30),
Gender VARCHAR(30),
Strength_Indicated INT,
Hoard INT,
Avatar_Level VARCHAR(30),
Skill VARCHAR(30),
Original_Owner VARCHAR(30),
Family_ID VARCHAR(10) NOT NULL,
Species_ID VARCHAR(10) NOT NULL,
Inventory_ID VARCHAR(30) NOT NULL,
Weapon_ID VARCHAR(10),
Player_ID VARCHAR(10) NOT NULL,
PRIMARY KEY (Avatar_ID));
CREATE TABLE Family (
Family_ID VARCHAR(10) NOT NULL,
Mother_ID VARCHAR(10) NOT NULL,
Father_ID VARCHAR(10) NOT NULL,
primary key(Family_ID)
);
CREATE TABLE Mother (
Mother_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Mother_ID)
);
CREATE TABLE Father (
Father_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Father_ID)
);
ALTER TABLE Avatars
ADD CONSTRAINT fk_Family_ID
FOREIGN KEY (Family_ID)
REFERENCES Family(Family_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Mother_ID
FOREIGN KEY (Mother_ID)
REFERENCES Mother(Mother_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Father_ID
FOREIGN KEY (Father_ID)
REFERENCES Father(Father_ID);
ALTER TABLE Father
ADD CONSTRAINT fk_Avatar_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
ALTER TABLE Mother
ADD CONSTRAINT fk_Avatars_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
INSERT INTO Avatars (Avatar_ID,Avatar_Name,AvA_DOB,Age,Gender,Strength_Indicated,Hoard,Avatar_Level, Skill, Original_Owner, Family_ID,Species_ID,Inventory_ID,Player_ID) VALUES
('Ava01','Verda','20-JAN-2014','1 year 2 months','Female','100','20','Master','Leader',' - ',' - ','DRA1','MasterInventory','Player07');
Thanks in advance for any help given! (:
Foreign key refers to a record in parent table. In your INSERT statement you are inserting value ' - ' into a column parent_id. In this error message oracle informs you that there is no record with value ' - ' in a column family_id of a table family. As I can understand, you are trying to use ' - ' as 'absence of value'. There is special value for that - NULL. So you need to write your statement as:
INSERT INTO Avatars (Avatar_ID, Avatar_Name, AvA_DOB,
Age, Gender, Strength_Indicated, Hoard, Avatar_Level, Skill,
Original_Owner, Family_ID, Species_ID, Inventory_ID, Player_ID)
VALUES ('Ava01', 'Verda', '20-JAN-2014', '1 year 2 months' ,'Female',
'100', '20', 'Master', 'Leader', NULL, NULL, 'DRA1',
'MasterInventory', 'Player07');
Also I can recommend some changes to your schema. First of all, use number data type for primary keys - it allows you to use sequences to generate unique values. Also, I don't know details of the problem, but "family relations" in your tables look a bit complicated. You can describe it in a single table:
create table family_tree (
person_id number primary key,
father_id number,
mother_id number,
sex char(1),
name varchar2(50),
family_name varchar2(50));
add constraint fk_mother_id foreign key (mother_id)
references family_tree (person_id);
add constraint fk_father_id foreign key (father_id)
references family_tree (person_id);

How to implement bidirectional referenced tables?

I have a table School and a table Teacher having a one-to-many relationship. However, one of the teachers is the school's principle, and only one teacher can be the school principle. So I thought of saving the teachers id (principle) in the School table as follows:
CREATE TABLE School (
ID INT PRIMARY KEY,
Name VARCHAR(40),
PrincipleID INT FOREIGN KEY REFERENCES Teacher.ID
)
CREATE TABLE Teacher (
ID INT PRIMARY KEY,
Name VARCHAR(40),
SchoolID INT FOREIGN KEY REFERENCES School.ID
)
I know I could loose the foreign key reference in the school table, but that's not an option.
Should I make the reference after the table creation? If yes, how?
Another solution is to create a new table, let's say SchoolsPrinciples with just two fields:
CREATE TABLE SchoolsPrinciples
(
SchoolId int,
TeacherId int,
CONSTRAINT uc_SchoolTeacher UNIQUE (SchoolId, TeacherId)
)
A UNIQUE constraint let you obtain exactly one teacher per each school.
When building the tables, you'll need to add the constraint as a separate alter statement. Note also that when creating foreign keys, you should only specify the table name, not the referenced column (the column is implied by the primary key).
CREATE TABLE School (
ID INT PRIMARY KEY,
Name VARCHAR(40),
PrincipleID INT);
CREATE TABLE Teacher (
ID INT PRIMARY KEY,
Name VARCHAR(40),
SchoolID INT
CONSTRAINT FK_Teacher_School
FOREIGN KEY REFERENCES School);
ALTER TABLE School add
CONSTRAINT FK_School_Teacher
FOREIGN KEY (PrincipleID) REFERENCES Teacher;
When you add data, you'll need to set the PrincipleID field as a separate update:
insert into School (ID, Name)
values (1, 'Blarg Elementary');
insert into Teacher (ID, Name, SchoolID)
values (1, 'John Doe', 1),
(2, 'Bob Smith', 1),
(3, 'Adam Walker', 1);
update School set PrincipleID = 2 where ID = 1;
Put a boolean IsPrincipal on the Teacher table instead. Or add a third relationship table
CREATE TABLE SchoolPrincipals (
INT SchoolID PRIMARY KEY FOREIGN KEY REFERENCES School.ID,
INT TeacherID FOREIGN KEY REFERENCES Teacher.ID
)
Keeps everything tidy without painful delete logic.
You can take a column in Teacher table as
IsPrincipal where only one row will have value as true as referred
by jonnyGold,
This can be checked by triggers.
OR
You can use filtered index if using Sql Server 2008.
Create unique filtered index where SchoolID, IsPrincipal
is NOT NULL and are unique
Boss where this will contain ID of principal hence creating employee manager relationship which in your case is not suitable.
CREATE TABLE EmpManager
(
TeacherID int
SchoolID int
IsPrincipal bit
)
And use filtered index or trigger to handle the scenario.
EDIT:
CREATE TABLE [dbo].[Teacher](
[ID] [int] NOT NULL primary key,
[Name] [varchar](40) NULL,
[SchoolID] [int] NULL,
)
GO
CREATE TABLE [dbo].[School](
[ID] [int] NOT NULL primary key,
[Name] [varchar](40) NULL,
[PrincipleID] [int] NULL,
)
GO
ALTER TABLE [dbo].[Teacher] WITH CHECK ADD CONSTRAINT [FK_Teacher_School] FOREIGN KEY([SchoolID])
REFERENCES [dbo].[School] ([ID])
GO
ALTER TABLE [dbo].[School] WITH CHECK ADD CONSTRAINT [FK_School_Teacher] FOREIGN KEY([PrincipleID])
REFERENCES [dbo].[Teacher] ([ID])
GO
Better design should be the one suggested by ADC