231k views
2 votes
Explain the term foreign key and give an example (Hint, for the example, provide two tables and show the relationship between them).

User Godfather
by
8.3k points

1 Answer

3 votes

Answer:

Foreign key is a part of the DBMS. It stands for a database management system.

Foreign key use can be given as:

It is key that used to link two tables together.

It used as a reference to the primary key.

To define any foreign key we references keyword.

Example:

A)

create table product

(

P_id number(4) primary key,

P_name varchar2(30),

);

insert into product(P_id ,P_name )values(1001,'X');

insert into product(P_id ,P_name)values(1003,'y');

insert into product(P_id ,P_name)values(1005,'z');

B)

create table productdetail

(

pd_id number(4) references P_id number(4) ,

pd_city varchar2(50),

pd_price number(5)

);

insert into productdetail(pd_id ,pd_city, pd_price)values(1001,'kanpur',2100);

insert into productdetail(pd_id ,pd_city, pd_price)values(1003,'delhi',1200);

insert into productdetail(pd_id ,pd_city, pd_price)values(1005,'agra',205);

C)

query for related data :

select * from product,productdetail where product.P_id=productdetail.pd_id;

Explanation:

In point A we declare a table i.e product. In this table, we create two-column P_id which is a primary key, P_name.

In point B we create a table i.e productdetail. In this table, we create three column pd_id which is a foreign key that works as a reference for the primary key,pd_city,pd_price.

In point C. It gives the data from both the table.

User Pkawiak
by
8.1k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.