16 Program for Foreign Key in PostgreSQL

Program:

create table customers(CID int primary key, name text, contact int);



create table orders(OID int primary key, item text, price int, status text, CID int references customers(CID));



\d orders;



insert into customers values(1, 'Jim', 5555),(2,'John',5555),(3,'Rob',5556);



insert into orders values(1, 'Book', 10, 'confirmed', 3);



insert into orders values(2, 'Aircon', 500, 'confirmed', 1);



insert into orders values(3, 'Table', 200, 'confirmed', 3);



insert into orders values(4, 'Fridge', 700, 'confirmed', 2);



select * from orders;



select * from orders where cid=(select cid from customers where name='Rob');


Output:

Create Table for Foreign Key
Insert Data into Foreign Key Tables
Use of Foreign Key

Previous
Next Post »