Foreign key in DBMS

Foreign key in DBMS

A foreign key in DBMS (Database Management System) is a field (or a set of fields) in one table that refers to the PRIMARY KEY of another table.
It is used to establish a relationship between two tables and ensures referential integrity—meaning the database prevents actions that would leave broken links between related tables.

1. Create BRAND Table

CREATE TABLE BRAND (
    BID INT PRIMARY KEY,
    BName VARCHAR(50),
    BType VARCHAR(50)
);

2. Insert Records into BRAND

INSERT INTO BRAND (BID, BName, BType) VALUES
(10, 'Dove', 'Soap'),
(11, 'Lux', 'Soap'),
(12, 'Ariel', 'Detergent'),
(13, 'Medimix', 'Soap');

3. Create PRODUCT Table

CREATE TABLE PRODUCT (
    PID INT PRIMARY KEY,
    PName VARCHAR(50),
    BID INT,
    Stock INT,
    UPrice INT,
    Rating INT,
    FOREIGN KEY (BID) REFERENCES BRAND(BID)
);

4. Insert Records into PRODUCT

INSERT INTO PRODUCT (PID, PName, BID, Stock, UPrice, Rating) VALUES
(1, 'Detergent Bar', 12,  60, 28, 3),
(2, 'Beauty Bar',    11, 143, 26, 4),
(3, 'Soap Bar',      10,  78, 20, 4),
(4, 'Soap Bar',      13,  55, 25, 5),
(5, 'Liquid Soap',   13,  70, 34, 3);

Answer the questions based on the following tables:

Table: Product

PCodePNameUPriceRatingBID
P01Shampoo1206M03
P02Toothpaste548M02
P03Soap257M03
P04Toothpaste654M04
P05Soap385M05
P06Shampoo2456M05

Table: Brand

BIDBName
M02Dant Kanti
M03Medimix
M04Pepsodent
M05Dove

(i) Display product name and brand name from the tables PRODUCT and BRAND
(ii) Display the structure of the table PRODUCT
(iii) Display the average rating of Medimix and Dove brands
(iv) Display the name, price, and rating of products in descending order of rating

(i) Display product name and brand name
SELECT PName, BName
FROM PRODUCT, BRAND
WHERE PRODUCT.BID = BRAND.BID;

(ii) Structure of PRODUCT table
DESC PRODUCT;

(iii) Display the average rating of Medimix and Dove brands
SELECT BName, AVG(Rating) AS AverageRating
FROM PRODUCT, BRAND
WHERE PRODUCT.BID = BRAND.BID
AND BName IN (‘Medimix’, ‘Dove’)
GROUP BY BName;

(iv) Display name, price, and rating in descending order of rating
SELECT PName, UPrice, Rating
FROM PRODUCT
ORDER BY Rating DESC;

Using NATURAL JOIN

(i) Product name and brand name

SELECT PName, BName
FROM PRODUCT NATURAL JOIN BRAND;

(iii) Average rating of Medimix and Dove**

SELECT BName, AVG(Rating) AS AverageRating
FROM PRODUCT NATURAL JOIN BRAND
WHERE BName IN ('Medimix', 'Dove')
GROUP BY BName;

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top