Unable to move primary key fields into foreign key? - sql

I've created to two tables name STUDENT and ROOM which in my case is a one to one relation. The primary key from STUDENT table is a foreign key in ROOM but when i insert data into student its doesn't update values in foreign key of room.
There were many similar question about this in mysql and sqlserver but not in oracle sql.

I believe you are looking for cascading updates.
Check out this article:-
http://tkyte.blogspot.com/2009/10/httpasktomoraclecomtkyteupdatecascade.html?m=1
The script from article generates a package and three triggers which will do cascade updates.

Related

how to make multiple foreign keys between two tables?

I am using sql server management studio and I have two tables, "City" and "Booking". In the booking table, there are two columns, "SourceCity" and "DestinationCity". I want to take two foreign keys from city table to Booking table for the above mentioned columns, but I don't know how to do it. I want to use this all for a stored procedure for adding new bookings as well. please help me out here.
I guess, youcan try something like this:
ALTER TABLE Booking
ADD CONSTRAINT FK_BookingSourceCity
FOREIGN KEY (SourceCity)
REFERENCES City (CityName);
ALTER TABLE Booking
ADD CONSTRAINT FK_BookingDestinationCity
FOREIGN KEY (DestinationCity)
REFERENCES City (CityName);
I assume CityName is a primary key in the table City

Insert into tables with primary and foreign key at same time

Very new to SQL and have spent a day on this already.
Here are my two tables:
Centre(cid, name, location, nurse_supervisor)
Nurse(nid, name, centre_id, certificate)
I have a big problem. The (nurse_supervisor) in Centre is a foreign key to Nurse (nid).
The (centre_id) in Nurse is a foreign key to (Centre cid).
I can't figure out how to populate these tables. I have tried:
INSERT ALL, which produces "A foreign key value has no matching primary key value"
I have tried removing the foreign key constraints and adding them after populating the tables but when I do that it says I can't add a constraint to tables with preexisting data.
I tried removing NOT NULL - but realized that was silly as the constraints will be enforced anyways.
Everything I look through says populate the parent table first and then the child, but these tables are linked to each other.
I am using SQL developer.
This is a poor schema design, but one way to get around it would be to:
Make both centre_id and nurse_supervisor columns NULL in the two table definitions
Insert all rows into both tables, but with NULL for those two columns
Update centre_id to the correct value for each row in the Nurse table
Update nurse_supervisor to the correct value for each row in the Centre table

In Oracle, how would I begin to create the tables when all the needed tables have both foreign and primary key constraint?

In Oracle,
Lets say there are 3 tables with primary key and foreign key on each table. So, If i were to start creating the tables, how would i start. I started to create a first table with primary and foreign key but It don't let me create a table when there is foreign key mentioned without creating other referenced table.
if this the case, I can't create any of this tables, Because i foreign key on all 3 tables and primary on each table.
Note: Yeah, I know i could add the constraint later. but i'm curious to know, how does thing kind of issue work in real world programming. do developers add the foreign constraint later or ummmm just curious.
You can declare the foreign key constraint to be DEFERRABLE, which allows you to have Oracle check the constraint at the end of a transaction.
SET TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO TABLE_ONE (PK1, FK2, NAME)
VALUES(10, 20, 'Foo');
INSERT INTO TABLE_TWO (PK2, FK3, NAME)
VALUES(20, 30, 'Bar');
INSERT INTO TABLE_THREE (PK3, FK1, NAME)
VALUES(30, 10, 'Baz');
COMMIT;
After each of the first two INSERTs, there is a foreign key with no referent, but Oracle won't check until the commit. After the third insert, everything is fixed.
Do you want this data structure though?
"Lets say there are 3 tables with primary key and foreign key on each
table. "
In the real world that couldn't happen. There must be at least one table which has no foreign key dependency on any other table.
In fact it's likely to be more complex than that. Most data models ave two sorts of tables: lookup (or code) tables and business data tables. There must be at least one business data table which doesn't depend on any other business data table, one which sits at the top of the tree.
"do developers add the foreign constraint later"
It depends. Generally speaking it is useful to have separate scripts for different sorts of DDL, so yes, it is common to create the tables in one pass, build indexes in another and add constraints afterwards. Such a strategy would be appropriate if the database phase includes data loading.
But if the delivered database will be empty - except for lookup data - the tables can be built in a singe script. In which case we need to order the script so that we build the tables without foreign key dependencies first, then build their children, then the grandchildren, and so on.

MS SQL creating many-to-many relation with a junction table

I'm using Microsoft SQL Server Management Studio and while creating a junction table should I create an ID column for the junction table, if so should I also make it the primary key and identity column? Or just keep 2 columns for the tables I'm joining in the many-to-many relation?
For example if this would be the many-to many tables:
MOVIE
Movie_ID
Name
etc...
CATEGORY
Category_ID
Name
etc...
Should I make the junction table:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
Movie_Category_Junction_ID
[and make the Movie_Category_Junction_ID my Primary Key and use it as the Identity Column] ?
Or:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
[and just leave it at that with no primary key or identity table] ?
I would use the second junction table:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
The primary key would be the combination of both columns. You would also have a foreign key from each column to the Movie and Category table.
The junction table would look similar to this:
create table movie_category_junction
(
movie_id int,
category_id int,
CONSTRAINT movie_cat_pk PRIMARY KEY (movie_id, category_id),
CONSTRAINT FK_movie
FOREIGN KEY (movie_id) REFERENCES movie (movie_id),
CONSTRAINT FK_category
FOREIGN KEY (category_id) REFERENCES category (category_id)
);
See SQL Fiddle with Demo.
Using these two fields as the PRIMARY KEY will prevent duplicate movie/category combinations from being added to the table.
There are different schools of thought on this. One school prefers including a primary key and naming the linking table something more significant than just the two tables it is linking. The reasoning is that although the table may start out seeming like just a linking table, it may become its own table with significant data.
An example is a many-to-many between magazines and subscribers. Really that link is a subscription with its own attributes, like expiration date, payment status, etc.
However, I think sometimes a linking table is just a linking table. The many to many relationship with categories is a good example of this.
So in this case, a separate one field primary key is not necessary. You could have a auto-assign key, which wouldn't hurt anything, and would make deleting specific records easier. It might be good as a general practice, so if the table later develops into a significant table with its own significant data (as subscriptions) it will already have an auto-assign primary key.
You can put a unique index on the two fields to avoid duplicates. This will even prevent duplicates if you have a separate auto-assign key. You could use both fields as your primary key (which is also a unique index).
So, the one school of thought can stick with integer auto-assign primary keys, and avoids compound primary keys. This is not the only way to do it, and maybe not the best, but it won't lead you wrong, into a problem where you really regret it.
But, for something like what you are doing, you will probably be fine with just the two fields. I'd still recommend either making the two fields a compound primary key, or at least putting a unique index on the two fields.
I would go with the 2nd junction table. But make those two fields as Primary key. That will restrict duplicate entries.

SQL delete query with foreign key constraint

I know that this question belongs to the very early stages of the database theory, but I have not encountered such a problem since several months. If someone has a database with some tables associated together as "chain" with foreign keys and they want to delete a record from a table which has some "dependent" tables, what obstacles arise? In particular, in a database with tables: Person, Profile, Preference, Filter exist the associations as Person.id is foreign key in Profile and Profile.id is foreign key in Preference and Filter.id is foreign key in Preference, so as that all the associationsenter code here are OneToMany. Is it possible to delete a Person with a simple query:
Delete from Person p where p.id= 34;
If no, how should look like the query in order to perform the delete successfully?
If the database in the application is managed by hibernate, what constraints (annotations) should I apply to the associated fields of each entity, so as to be able with the above simple query to perform the delete?
FOR SQL VERSION
Look at the Screenshot. you can use the Insert Update Specificaiton Rules. as it has Delete and Update Rules. you can set either of these values.
Foreign key constraints may be created by referencing a primary or unique key. Foreign key constraints ensure the relational integrity of data in associated tables. A foreign key value may be NULL and indicates a particular record has no parent record. But if a value exists, then it is bound to have an associated value in a parent table. When applying update or delete operations on parent tables there may be different requirements about the effect on associated values in child tables. There are four available options in SQL Server 2005 and 2008 as follows:
No Action
Cascade
SET NULL
SET Default
Use this article for Refrence.
http://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
ORACLE VERSION
you can use one of below.
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete no action;
alter table sample1
add foreign key (col1)
references
sample (col2)
on delete restrict;
alter table sample1
add foreign key (col1)
references sample (col2)
on delete cascade;
for refrance.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm
answer is no if there is foreign key constraint then you have to delete leaf node table data first
that is first delete from Preference table
then from Profile and Filter Table
then delete record from Person table
This is the generic concept that you apply anywhere