0% found this document useful (0 votes)
3 views11 pages

Rdbms Lab.docx

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

PROGRAM 1

STEP 1. Start the program


STEP 2. Connect to the database `CollegeDB`.
STEP 3. Create the table `CollegeData` with relevant fields.
STEP 4. Populate the table with data.
STEP 5. Query: SELECT * FROM CollegeData WHERE PassPercentage > 75 AND Organization =
'INFOSYS'. After Display the result.
STEP 7. Query: SELECT SUM(PlacedStudents) AS TotalPlacedStudents FROM CollegeData
WHERE Course = 'BCA'.
STEP 8. Display the result as "Total Placed Students in BCA".
STEP 9. Query: SELECT * FROM CollegeData
WHERE PassPercentage = (SELECT MAX(PassPercentage) FROM CollegeData).
STEP 10. Display the result as "Course with Highest Pass Percentage".
STEP 11. Stop the program
Step 1: Create the Database and Table
CREATE DATABASE CollegeDB;

USE CollegeDB;

CREATE TABLE CollegeData (


CollegeName VARCHAR(255),
Course VARCHAR(100),
NoOfStudents INT,
NoOfStudentsPassed INT,
PassPercentage FLOAT,
Organization VARCHAR(255),
PlacedStudents INT
);

Step 2: Insert Sample Data


INSERT INTO CollegeData (CollegeName, Course, NoOfStudents, NoOfStudentsPassed,
PassPercentage, Organization, PlacedStudents)
VALUES
('XYZ College', 'BCA', 120, 100, 83.33, 'INFOSYS', 80),
('ABC College', 'B.Tech', 200, 150, 75.00, 'TCS', 100),
('LMN College', 'MCA', 90, 85, 94.44, 'INFOSYS', 70),
('PQR College', 'BCA', 130, 100, 76.92, 'WIPRO', 60),
('DEF College', 'MBA', 50, 45, 90.00, 'INFOSYS', 35);

Step 3: Queries
a) Display the student details whose pass percentage is above 75 and who were placed in INFOSYS.

SELECT *
FROM CollegeData
WHERE PassPercentage > 75 AND Organization = 'INFOSYS';

b) Find the total number of students placed from the BCA department.

SELECT SUM(PlacedStudents) AS TotalPlacedStudents


FROM CollegeData
WHERE Course = 'BCA';
c) Display the details of the course having the highest pass percentage.
SELECT *
FROM CollegeData
WHERE PassPercentage = (SELECT MAX(PassPercentage) FROM CollegeData);

PROGRAM 2
STEP 1. Start the program.
STEP 2. Create the database (if not already created).
STEP 3. Create the Employee table with the specified fields.
STEP 4. Insert employee records into the table.
STEP 5. Query: SELECT COUNT(*) FROM Employee WHERE DateOfJoining < '2020-01-01'.
STEP 6. Store the count as the result for Task (a).

STEP 7. Query: SELECT * FROM Employee WHERE EmpName LIKE 'S%' OR EmpName LIKE
'P%'.
STEP 8. Store the rows as the result for Task (b).
STEP 9. Query: SELECT * FROM Employee ORDER BY Grade.
STEP 10. Store the sorted rows as the result for Task (c).
STEP 11. Display results for Tasks (a), (b), and (c).
STEP 12. Stop the program.
Step 1: Create the Employee Table
CREATE TABLE Employee (
EmpCode INT PRIMARY KEY,
EmpName VARCHAR(255),
Address VARCHAR(255),
Designation VARCHAR(100),
DateOfJoining DATE,
Grade CHAR(1)
);
Step 2: Insert Sample Data
INSERT INTO Employee (EmpCode, EmpName, Address, Designation, DateOfJoining, Grade)
VALUES
(101, 'Sam', 'New York', 'Manager', '2018-05-10', 'A'),
(102, 'Paul', 'Chicago', 'Developer', '2019-07-15', 'B'),
(103, 'Steve', 'Dallas', 'Analyst', '2021-03-20', 'C'),
(104, 'Peter', 'Boston', 'Tester', '2017-11-05', 'B'),
(105, 'Sophia', 'Miami', 'HR', '2020-09-12', 'A'),
(106, 'Pam', 'Austin', 'Developer', '2019-01-25', 'C');

Queries
a) Find the number of employees who joined before 2020.
SELECT COUNT(*) AS NumEmployeesBefore2020
FROM Employee
WHERE DateOfJoining < '2020-01-01';
b) Display the employee details whose names Start the program with 'S' or 'P'.
SELECT *
FROM Employee
WHERE EmpName LIKE 'S%' OR EmpName LIKE 'P%';
c) Arrange the employees as per their grade level
SELECT *
FROM Employee
ORDER BY Grade;
PROGRAM 3
STEP 1. Start the program.
STEP 2. Connect to the database.
STEP 3. Create the `client_master` table:
STEP 4. Define the fields: `client_no`, `name`, `address`, `city`, `state`, `pincode`, `remarks`,
`bal_due`.
STEP 5. Specify appropriate data types for each field.
STEP 6. Create the `supplier_master` table:
STEP 7. Use `CREATE TABLE supplier_master AS SELECT ...` to copy structure from
`client_master`.
STEP 8. Rename `client_no` to `supplier_no` and `name` to `supplier_name`.
STEP 9. Insert data into `client_master`:
STEP 10. Prepare sample data for fields.
STEP11. Execute the `INSERT INTO client_master` query to add rows.
STEP 12. Insert data into `supplier_master` from `client_master`:
STEP 13. Use `INSERT INTO supplier_master SELECT ...` query to copy data.
STEP 14. Verify the mapping of fields during insertion.
STEP 15. Delete a specific row from `client_master`:
STEP 16. Identify the row to be deleted based on a condition (e.g., `client_no`).
STEP 17. Execute the `DELETE FROM client_master WHERE client_no = <value>` query.

STEP 18. Display the updated data:


STEP 19. Stop the program.
Step 1: Create the client_master Table
CREATE TABLE client_master (
client_no INT PRIMARY KEY,
name VARCHAR(255),
address VARCHAR(255),
city VARCHAR(100),
state VARCHAR(100),
pincode INT,
remarks VARCHAR(255),
bal_due DECIMAL(10, 2)
);

Step 2: Create the supplier_master Table


Create the supplier_master table by copying all fields from client_master and renaming client_no to
supplier_no and name to supplier_name.

CREATE TABLE supplier_master AS


SELECT
client_no AS supplier_no,
name AS supplier_name,
address,
city,
state,
pincode,
remarks,
bal_due
FROM client_master
WHERE 1=0; -- Ensures the structure is created but no data is copied

Step 3: Queries
a) Insert data into client_master

INSERT INTO client_master (client_no, name, address, city, state, pincode, remarks, bal_due)
VALUES
(1, 'Alice', '123 Elm St', 'New York', 'NY', 10001, 'Premium Client', 5000.00),
(2, 'Bob', '456 Oak St', 'Los Angeles', 'CA', 90001, 'Regular Client', 1500.00),
(3, 'Charlie', '789 Pine St', 'Chicago', 'IL', 60001, 'Delayed Payments', 2000.00);
b) Insert data into supplier_master from client_master
INSERT INTO supplier_master (supplier_no, supplier_name, address, city, state, pincode, remarks,
bal_due)
SELECT client_no, name, address, city, state, pincode, remarks, bal_due
FROM client_master;
c) Delete a selected row in client_master
To delete a specific row (e.g., for client_no = 2)
DELETE FROM client_master
WHERE client_no = 2;
PROGRAM 4
STEP 1. Start the program.
STEP 2. Connect to the database.
STEP 3 Create the ` orders’ table: `order_no`, `product_no`, `client_no`, `delivery_address`,
`delivery_date`, `order_status`. Set the primaryKey order_no
STEP 4. Create the `sales_order` table: `s_order_no`, `product_no`, `client_no`, `delivery_address`,
`delivery_date`, `order_status`. And Set the composite primary key (`s_order_no`, `product_no`).
after Execute the `CREATE TABLE` query.
STEP 4. Add a new column `salesman_no` to Execute `ALTER TABLE sales_order ADD
salesman_no INT`and Set `s_order_no` as a foreign key
STEP 5 :Column Constraint to Identify the parent table (`orders`) with `order_no` as primary key then
Execute `ALTER TABLE sales_order ADD CONSTRAINT fk_s_order_no FOREIGN KEY
(s_order_no) REFERENCES orders(order_no)`.
STEP 6: Table Constraint to Define a foreign key constraint at the table level for `s_order_no`.
and Execute `ALTER TABLE sales_order ADD CONSTRAINT fk_s_order_no_table FOREIGN
KEY (s_order_no) REFERENCES orders(order_no)`.
STEP 7: Enforce integrity rules using `CHECK`:
STEP 8:Restrict `order_status` to valid values to Execute `ALTER TABLE sales_order ADD
CONSTRAINT chk_order_status CHECK (order_status IN ('Pending', 'Completed', 'Cancelled'))`.
STEP 9: Ensure `delivery_date` is not in the past to Execute `ALTER TABLE sales_order ADD
CONSTRAINT chk_delivery_date CHECK (delivery_date >= CURRENT_DATE)`.
STEP 10. Display the final table structure using `DESCRIBE sales_order` or equivalent.
STEP 11. Stop the program.
Step 1: Create the sales_order Table and Order table
CREATE TABLE sales_order (
s_order_no INT,
product_no INT,
client_no INT,
delivery_address VARCHAR(255),
delivery_date DATE,
order_status VARCHAR(50),
PRIMARY KEY (s_order_no, product_no)
);
Step 1: Create the order Table
CREATE TABLE orders (
order_no INT,
product_no INT,
client_no INT,
delivery_address VARCHAR(255),
delivery_date DATE,
order_status VARCHAR(50),
PRIMARY KEY (order_no, product_no)
);

Step 2: Queries for Tasks


a) Add a new column for storing the salesman number
ALTER TABLE sales_order
ADD salesman_no INT;
b) Set s_order_no as a foreign key (column constraint)
Assuming there is a orders table where order_no is the primary key:
ALTER TABLE sales_order
ADD CONSTRAINT fk_s_order_no
FOREIGN KEY (s_order_no) REFERENCES orders(order_no);
c) Set s_order_no as a foreign key (table constraint)
If the foreign key is not defined during creation, you can define it at the table level. This example
assumes the reference is also to an orders table:
ALTER TABLE sales_order
ADD CONSTRAINT fk_s_order_no_table
FOREIGN KEY (s_order_no) REFERENCES orders(order_no);
d) Enforce the integrity rules using CHECK
Example: Ensuring order_status can only have specific values (e.g., 'Pending', 'Completed',
'Cancelled'):
ALTER TABLE sales_order
ADD CONSTRAINT chk_order_status
CHECK (order_status IN ('Pending', 'Completed', 'Cancelled'));
Another example: Ensuring delivery_date cannot be a past date:
ALTER TABLE sales_order
ADD CONSTRAINT chk_delivery_date
CHECK (delivery_date >= CURRENT_DATE);

PROGRAM 5
STEP 1. Start the program.
STEP 2. Connect to the database.
STEP 3. Create the `student_master` table, the fields are `name` VARCHAR,’regno` INT PRIMARY
KEY,`dept` VARCHAR, `year` INT after Execute the `CREATE TABLE student_master` query.
STEP 4: Select the student’s name column to Execute `SELECT name FROM student_master`.
STEP 5: Eliminate duplicate entries to Create a temporary table with distinct rows using `SELECT
DISTINCT *` by Delete all rows from `student_master` using `DELETE`.
STEP 6:Copy data from the temporary table back to `student_master` then Drop the temporary
table.
STEP 7: Sort the table alphabetically to Execute `SELECT * FROM student_master ORDER BY
name ASC`.
STEP 8: Select students of a particular department by Execute `SELECT * FROM student_master
WHERE dept = '<department_name>'`.
STEP 9: Display the results of each query.
STEP 10: Stop the program.

Step 1: Create the student_master Table


CREATE TABLE student_master (
name VARCHAR(255),
regno INT PRIMARY KEY,
dept VARCHAR(100),
year INT
);

Step 2: Queries for the Tasks


a) Select the student’s name column
sql
Copy code
SELECT name FROM student_master;
b) Eliminate the duplicate entries in the table
To remove duplicate entries:
1.​ Create a temporary table containing distinct records:
CREATE TABLE temp_student_master AS
SELECT DISTINCT * FROM student_master;
2.​ Delete all rows in the original table:
DELETE FROM student_master;
3.​ Copy data back into the original table:
INSERT INTO student_master
SELECT * FROM temp_student_master;
4.​ Drop the temporary table:
DROP TABLE temp_student_master;

c) Sort the table in alphabetical order (by name)


SELECT * FROM student_master
ORDER BY name ASC;

d) Select all students of a particular department


Replace <department_name> with the desired department (e.g., 'CSE'):
SELECT * FROM student_master
WHERE dept = '<department_name>';

PROGRAM 6
STEP 1. Start the program.
STEP 2. Connect to the database.
STEP 3. Create the `sales_order_details` table fields are `s_order_no` INT PRIMARY KEY,
`product_no` INT, `description` VARCHAR, `qty_ordered` INT,’qty_disp` INT,`product_rate`
DECIMAL,`profit_percent` DECIMAL, `sell_price` DECIMAL, `supplier_name` VARCHAR then
Execute query.

STEP 4. Perform the required queries:


a. Compute `sell_price * 0.50` and `sell_price * 1.50`:
i. Execute:
`SELECT s_order_no, product_no, sell_price, sell_price * 0.50, sell_price * 1.50 FROM
sales_order_details`.

b. Select rows where `profit_percent` is not between 10 and 20:


i. Execute:
`SELECT product_no, profit_percent, sell_price FROM sales_order_details WHERE
profit_percent NOT BETWEEN 10 AND 20`.

c. Select rows where `profit_percent` is not between 20 and 30:


i. Execute:
`SELECT product_no, description, profit_percent, sell_price FROM sales_order_details
WHERE profit_percent NOT BETWEEN 20 AND 30`.

d. Select rows where `supplier_name` has 'r' or 'h' as the second character:
i. Execute:
`SELECT supplier_name, product_no FROM sales_order_details WHERE supplier_name LIKE
'_r%' OR supplier_name LIKE '_h%'`.

STEP 5. Display results for each query.


STEP 6. Stop the program.
Step 1: Create the sales_order_details Table
CREATE TABLE sales_order_details (
s_order_no INT PRIMARY KEY,
product_no INT,
description VARCHAR(255),
qty_ordered INT,
qty_disp INT,
product_rate DECIMAL(10, 2),
profit_percent DECIMAL(5, 2),
sell_price DECIMAL(10, 2),
supplier_name VARCHAR(255)
);

Step 2: Queries for the Tasks


a) Select each row and compute sell_price * 0.50 and sell_price * 1.50 for each row
SELECT s_order_no, product_no, sell_price,
(sell_price * 0.50) AS fifty_percent_price,
(sell_price * 1.50) AS one_fifty_percent_price
FROM sales_order_details;

b) Select product_no, profit_percent, and sell_price where profit_percent is not between 10 and 20
(both inclusive)
SELECT product_no, profit_percent, sell_price
FROM sales_order_details
WHERE profit_percent NOT BETWEEN 10 AND 20;

c) Select product_no, description, profit_percent, and sell_price where profit_percent is not between
20 and 30
SELECT product_no, description, profit_percent, sell_price
FROM sales_order_details
WHERE profit_percent NOT BETWEEN 20 AND 30;

d) Select supplier_name and product_no where supplier_name has ‘r’ or ‘h’ as the second character
SELECT supplier_name, product_no
FROM sales_order_details
WHERE supplier_name LIKE '_r%' OR supplier_name LIKE '_h%';

Program 7.a
STEP 1. Start the program.
STEP 2. Declare variables as a INT := 0, b INT := 1, temp INT, n INT, i INT
STEP 3. Display the message: "Enter N".
STEP 4. Accept the value of n from the user.
STEP 5. Display the message: "Fibonacci series is:".
STEP 6. Display the value of a (0).
STEP 7. Display the value of b (1).
STEP 8. For i = 2 to n to Calculate temp = a + b , Update a := b, Update b := temp and Display the
value of temp.
STEP 9. Stop the program.

declare
a int := 0;
b int := 1;
temp int;
n int;
i int;
begin
dbms_output.put_line('Enter N');
n:=:n;
dbms_output.put_line('fibonacci series is :');
dbms_output.put_line(a);
dbms_output.put_line(b);
for i in 2..n
loop
temp:= a + b;
a := b;
b := temp;
dbms_output.put_line(temp);
end loop;
end;
Program 7.b
STEP 1. Start the program.
STEP 2. Declare variables as n INT ,fact INT := 1, i INT
STEP 3. Display the message: "Factorial".
STEP 4. Display the message: "Enter N".
STEP 5. Accept the value of n from the user.
STEP 6. Initialize fact to 1.
STEP 7. For i = 1 to n then Multiply fact by i after Update fact to the result of i * fact.
STEP 8. Display the message: "Result =" concatenated with the value of fact.
STEP 9. Stop the program.

declare
n int;
fact int:=1;
i int;
begin
dbms_output.put_line('Factorial');
dbms_output.put_line('Enter N');
n:=:n;
for i in 1..n
loop
fact:=i*fact;
end loop;
dbms_output.put_line('Result ='||fact);
end
PROGRAM 8
STEP 1. Start the program.
STEP 2. Create the table `userdetailsnew` with the following fields as usname (VARCHAR(20))
Primary Key, address (VARCHAR(300)), phno (NUMBER(10)).
STEP 3. Insert the following data into `userdetailsnew`
STEP 4. Create the procedure `getaddress` with the following parameters as Input: `p_pno` (Phone
number). And Output: `p_name` (User's name), `p_address` (User's address).
STEP 5. Procedure Logic:
a. Select the `usname` and `address` from `userdetailsnew` where `phno` = `p_pno`.
b. Store `usname` in `p_name` and `address` in `p_address`.
STEP 6. Declare variables as `uname` (user's name),`address` (user's address), `pno` (phone number
input).
STEP 7. Accept the phone number (`pno`) from the user.
STEP 8. Call the procedure `getaddress` passing `pno`. The procedure will return `usname` and
`address` into `uname` and `address`.
STEP 9. Display the following:
- Entered Phone Number: `pno`
- User Name: `uname`
- Address: `address`

STEP 10. Stop the program

create table userdetailsnew(usname varchar(20) primary key,address varchar(300),phno number(10));

insert into userdetailsnew values('iswariya','no 1 shathi nagar coimbatore','9865896598')


insert into userdetailsnew values('abinaya','no 2 thendarl nagar coimbatore','7855896598')

create or replace procedure getaddress (p_name out userdetailsnew.usname% TYPE,p_address out


userdetailsnew.address% TYPE,p_pno in userdetailsnew.phno% TYPE)
as
begin
select userdetailsnew.usname,userdetailsnew.address into p_name,p_address from userdetailsnew
where userdetailsnew.phno=p_pno;
end;

declare
uname userdetailsnew.usname%TYPE;
address varchar(300);
pno number(10);
begin
pno:=:Enterpno;
getaddress(uname,address,pno);
dbms_output.put_line('Entered Pho:'||pno);
dbms_output.put_line('User Name:'||uname);
dbms_output.put_line('Address:'||address);
end;

PROGRAM 9

STEP1. Start the program


STEP 2. Create the table `inventory` with the following fields as `pro_no`: VARCHAR(20),
PRIMARY KEY, `prod_name`: VARCHAR(300),`rate`: NUMBER(10),
STEP 3. Insert data into `inventory` table as Insert ('101', 'Widget A', 100),Insert ('102', 'Widget B',
150)
STEP 4. Begin PL/SQL Block to Update the `rate` for each product by 20% by `rate = rate + (rate *
0.20)`
STEP 5. Commit the changes using `COMMIT`.
STEP 6. Output the message: "Rates updated by 20% successfully."
STEP 7. Handle exceptions using the `EXCEPTION` block , If there is an error during the
`UPDATE`, rollback the transaction using `ROLLBACK`.
STEP 8. Output the error message: "Error occurred while updating rates."
STEP 9. Stop the program

create table inventory (pro_no varchar(20) primary key,Prod_name varchar(300),rate number(10));

insert into inventory values( 101,’Widget A’,100)


insert into inventory values( 102,’Widget B’,150)

DECLARE

BEGIN
UPDATE inventory
SET rate = rate + (rate * 0.20);
COMMIT;

dbms_output.put_line('Rates updated by 20% successfully.');


EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
dbms_output.put_line('Error occurred while updating rates.');
STOP THE PROGRAM;

PROGRAM 10
Step 1: Start the program the program the program
Step 2: Create the student Table by using CREATE TABLE student_master (name VARCHAR(255),
regno INT PRIMARY KEY, dept VARCHAR(100), year INT, marks INT
);
Step 3: To insert the value by INSERT INTO student (name, regno, dept, year, marks) VALUES
('John Doe', 101, 'Computer Science', 2, 78);
Step 4:create or replace trigger prevent_high_marks_insert to Creates the trigger with the name
prevent_high_marks_insert then CREATE OR REPLACE ensures that if a trigger with the same
name already exists, it will be replaced.
Step 5: before insert on student to specifies that the trigger will fire before any insert operation on the
student table.
Step 6: for each row -The trigger will fire for each row inserted into the student table.
Step 7: if :new.marks > 75 then NEW keyword refers to the new value being inserted into the row.
If the value of marks in the new row exceeds 75, the condition will be true.
Step 8: raise_application_error(-20001, 'Marks cannot be greater than 75'),If the condition is met
(marks > 75), an error is raised using RAISE_APPLICATION_ERROR, which will stop the insertion
and display the message 'Marks cannot be greater than 75'.
Step 9: end if to Ends the conditional block.
Step 10: Stop the program

Create the student Table


CREATE TABLE student_master (
name VARCHAR(255),
regno INT PRIMARY KEY,
dept VARCHAR(100),
year INT, marks INT
);
INSERT INTO student_master (name, regno, dept, year, marks) VALUES ('John Doe', 101,
'Computer Science', 2,78);
INSERT INTO student_master (name, regno, dept, year, marks) VALUES ('Jane Smith', 102,
'Mechanical Engineering', 3,70);

CREATE OR REPLACE TRIGGER prevent_high_marks_insert


BEFORE INSERT ON student
FOR EACH ROW
BEGIN
IF :NEW.marks > 75 THEN
RAISE_APPLICATION_ERROR(-20001, 'Marks cannot be greater than 75');
END IF;
STOP THE PROGRAM;

You might also like