PostgreSQL: Add constraint with mulitple conditions - sql

I'm having difficulties adding a constraint with two constraint conditions to an already existing table. I'm working with the two relations below, and I'm trying to add the constraint to the "books" table.
The relations are:
books((book_id), title, author_id, subject_id)
subjects((subject_id), subject, location)
Where the keys within the parantheses are primary keys, and the italics are foreign keys.
The first criteria/condition is that the subject_id is NOT NULL, and that the subject_id when inserting a new book-tuple into books, already has to exist as a primary key in the subjects relation.
ALTER TABLE books ADD CONSTRAINT hasSubject
CHECK(subject_id IS NOT NULL AND subject_id REFERENCES subjects(subject_id))
I keep getting the error message: "syntax error at or near 'REFERENCES'"
Any ideas? Thank you in advance!

REFERENCES is a separate type of constraint. So, you need two constraints:
ALTER TABLE books ADD CONSTRAINT chk_books_subject_id
CHECK (subject_id IS NOT NULL);
ALTER TABLE books ADD CONSTRAINT fk_books_subject_id
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);
I put these in two ALTER TABLE statements, to emphasize that they are different. They can be combined in one statement.
EDIT:
In one statement:
ALTER TABLE books
ADD CONSTRAINT chk_books_subject_id CHECK (subject_id IS NOT NULL),
ADD CONSTRAINT fk_books_subject_id FOREIGN KEY (subject_id) REFERENCES subjects(subject_id);

Related

Create a table in SQL where the Composite Primary Key is also a Foreign Key

I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.
: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number = 4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.
Tables Thanks in advance for all your help.
CREATE TABLE LFM_Enroll (
Student_ID char(7),
Section_Number char(4),
constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)
);
Your foreign key constraints are not right. You are trying to map two columns {Student_ID,Section_Number} to a single column LFM_Student.Student_ID.
The number of columns in the principal key must match the number of columns in the foreign key. In other words, the key LFM_Student is one column (Student_ID), so the foreign key also needs to be a single matching column - in this case LFM_Enroll.Student_ID. Correct DDL would be:
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Section_Number) references LFM_Section (Section_Number)
I'm not quite sure why your RDBMS is allowing what you have, but it may be using the first column and simply ignoring the second. In which case FK_LFM_Enroll_Section_Number is creating a foreign key LFM_Enroll.Student_ID => LFM_Section.Section_Number.
The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.
[Edit: For defining constraints refer lc.'s post]

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

How to add unique constraint as foreign key ?

I am trying to add unique constraint as foreign key by this statement:
ALTER TABLE SOME_TABLE ADD(
CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID) UNIQUE (S_ID)
);
I thought that this statement is correct, but all time I got "missing right parenthesis error". Probably I have wrong order of key words.
Could you give me advice how to create an unique constraint ?
I red this issue:
Add a unique constraint of a sql table as foreign key reference to an another sql table
but still I have problem with this.
First, you don't need parentheses. Second, this is two constraints and you might as well give both names:
ALTER TABLE SOME_TABLE
ADD CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID);
ALTER TABLE SOME_TABLE
ADD CONSTRAINT UNQ_ST_S_ID UNIQUE (S_ID);

Is there any way to make the following sql query work?

I am trying to create two tables using the following SQL:
create table student(sid char(20) primary key,name char(20),age int,hours char(10) references courses(cid));
create table courses(cid char(10),cname char(10),grader char(20) references student(sid));
However I get the following error:
1: ERROR: relation "courses" does not exist
3: ERROR: relation "student" does not exist
Is there any way or syntax which can solve this problem?
You would need to create the tables first (without REFERENCES clause). After that create your foreign keys manually by statement ALTER TABLE mytable ADD CONSTRAINT mytablefk FOREIGN KEY... But first I'd consider if there really is a relationship from table courses to table student!
Rather than creating the Foreign Key constraints at the same time as the tables with the References short-hand, you can add one or both of them afterwards with an Alter Table Add Constraint command. See the Alter Table page in the PostgrSQL manual here.
As mu pointed out, the target of a foreign key has to have a Unique or Primary Key constraint defined, so I've added that on the cid column in the example below.
In your case, it could look something like this:
create table student(sid char(20) primary key,name char(20),age int,hours char(10));
create table courses(cid char(10) primary key,cname char(10),grader char(20));
Alter Table student Add Constraint fk_student_hours_cid Foreign Key (hours) References courses(cid);
Alter Table courses Add Constraint fk_courses_grader_sid Foreign Key (grader) References student(sid);

error with cross referenced foreign key constraints

I had a weird problem when I am trying to create tables in MySQL.
I want to have a cross reference two many-to-many tables and here is the code I create table
create table teacher(
t_id char(10) not null unique,
name varchar(20) not null,
sur_name varchar(20) not null,
CONSTRAINT pk_teacher PRIMARY KEY(t_id))
create table student(
s_id char(10) not null unique,
name varchar(20) not null,
sur_name varchar(20) not null,
CONSTRAINT pk_student PRIMARY KEY(s_id))
create table teacher_student(
t_id char(10) not null,
s_id char(10) not null,
CONSTRAINT pk_teacher_student PRIMARY KEY(t_id, s_id))
in order to add foreign constraints I used the following code
ALTER TABLE teacher_student
ADD CONSTRAINT fk_teacher_student FOREIGN KEY(s_id) REFERENCES student(s_id)
ALTER TABLE teacher_student
ADD CONSTRAINT fk_student_teacher FOREIGN KEY(t_id) REFERENCES teacher(t_id)
ALTER TABLE student
ADD CONSTRAINT fk_student_teacher_student
FOREIGN KEY(s_id) REFERENCES teacher_student(s_id)
ALTER TABLE teacher
ADD CONSTRAINT fk_teacher_teacher_student
FOREIGN KEY(t_id) REFERENCES teacher_student(t_id)
that works fine but if I try to execute code in a different order like this
ALTER TABLE student
ADD CONSTRAINT fk_student_teacher_student
FOREIGN KEY(s_id) REFERENCES teacher_student(s_id)
ALTER TABLE teacher
ADD CONSTRAINT fk_teacher_teacher_student
FOREIGN KEY(t_id) REFERENCES teacher_student(t_id)
ALTER TABLE teacher_student
ADD CONSTRAINT fk_teacher_student FOREIGN KEY(s_id) REFERENCES student(s_id)
ALTER TABLE teacher_student
ADD CONSTRAINT fk_student_teacher FOREIGN KEY(t_id) REFERENCES teacher(t_id)
ALTER TABLE student
I am getting exception
Can't create table 'test.#sql-44c_37' (errno: 150)
My question is, why the order is important? what is the difference between these two ways of creating constraints? thanks
"I try to execute code in a different order like this" You have no different order you have extremely different constraints. You can't create such constraints.
Examine this article for more information
FOREIGN KEY Constraints
Some of your foreign keys don't seem to make any sense.
Those referencing student and teacher (the fk_teacher_student and fk_student_teacher ones) are fine. That's actually a typical case of a many-to-many table referencing each of the two entity tables whose many-to-many relationship is being implemented.
Now, what are you proposing with referencing back from those tables to the many-to-many one? I admit that I can't really explain why the foreign keys were successfully added using the first script and failed with the other. Sorry about that. Even though I've got some vague idea, that's not really the point of my answer. The point is, your present design is going to make it difficult for you to add new data. With it, you can't really add, say, a student without adding also a relationship between the new student and an existing teacher. This is because a row in student is supposed to reference an existing student in teacher_student, but since it is a new student, there's no corresponding row in teacher_student yet. Same goes for a new teacher.
So, consider just abandoning the idea of fk_student_teacher_student and fk_teacher_teacher_student. They are not needed to your design. They have already caused you to solve an unnecessary problem and they are likely to cause more trouble in the future.