0% found this document useful (0 votes)
4 views

Adbms File

This document is a practical file for a Master of Computer Application course at I.K. Gujral Punjab Technical University, focusing on database management systems. It includes tasks such as installing MySQL, creating tables with constraints, inserting records, and performing SQL queries. The document outlines various SQL commands and operations related to database management, including creating and manipulating tables, updating records, and querying data.

Uploaded by

Anu Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Adbms File

This document is a practical file for a Master of Computer Application course at I.K. Gujral Punjab Technical University, focusing on database management systems. It includes tasks such as installing MySQL, creating tables with constraints, inserting records, and performing SQL queries. The document outlines various SQL commands and operations related to database management, including creating and manipulating tables, updating records, and querying data.

Uploaded by

Anu Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

I.K.

Gujral Punjab
Technical University

Master Of Computer Application

Database management system


PRACTICAL FILE
For
1st Semester

SUBMITTED TO
SUBMITTED BY

DR. DINESH GUPTA

(Roll No.)
INDEX

SR.NO. TASK PAGE NO. REMARKS

1.

i)

2.

3.

4.

5.
6.

7.

8.

9.

10.

11.

12.

13.

14.

15.
TASK -1

STEPS TO INSTALL MYSQL


1. Go to browser and search for download mysql server and then click on the link
dev.mysql.com/downloads/mysql. This will bring you the following page.

2. Now click on the Windows(X86, 32 & 64 bit), ZIP Archive. And this will
redirect you to the next page which is shown below.

3. Then click on the Download button shown in the red box in the above video and
this will download the MySql installer. Then click and open the installer
to start the installation.

4. Read the License Agreement. Then click on I accept the license term and then
click on the next and following screen will be shown.
5. In the above image you will see some options. For customized server click on
the custom and hit the Next button. Then you will see the following screen.

Then click on the extension button to expand the given options. Select MySQL Server latest version and
click on the arrow button in the red box. Then it will look like the following. The option you choose will
come to the right side.

6. Then it will look like the image as above, we need three things to install. a)
MySql Server
b) MySql shell and c) MySql Workbench
And then click on the next button. Then click on the Execute and it will start
downloading all the things you have selected in this step.
7. Once it downloaded click on next button 3-4 times and you will see the
following page. Where it will ask you to create a password for your Sql server.
Then enter your password and confirm your password by re-entring it. Then
click on the next button. This password is used to open the MySql server.
8. Then you will see the following screen, click on the execute and it will apply
some configuration steps as shown in the image. Once it will completed, click
on next and then click on the finish.

9. MySQL has been installed successfully and now you can run SQL queries on
both command line and Workbench to store the data.

10. Read the License Agreement. Then click on I accept the license term and
then click on the next and following screen will be shown.

11.In the above image you will see some options. For customized server click on
the custom and hit the Next button. Then you will see the following screen.
Then click on the extension button to expand the given options. Select MySQL Server latest version and
click on the arrow button in the red box. Then it will look like the following. The option you choose will
come to the right side.

12. Then it will look like the image as above, we need three things to install. c)
MySql Server
d) MySql shell and
e) MySql Workbench
And then click on the next button. Then click on the Execute and it will start
downloading all the things you have selected in this step.
13. Once it downloaded click on next button 3-4 times and you will see the
following page. Where it will ask you to create a password for your Sql
server.
Then enter your password and confirm your password by re-entring it.
Then click on the next button. This password is used to open the MySql
server.
14. Then you will see the following screen, click on the execute and it will
apply some configuration steps as shown in the image. Once it will
completed, click on next and then click on the finish.

15. MySQL has been installed successfully and now you can run SQL queries
on both command line and Workbench to store the data.
TASK -2

Create tables with all required constraints as per the ER


diagram above, insert 5 records each in 3 tables, write atleast 3
conditional updates, use select command to display data of all
3 tables.
Remove curly braces({}) change the text between it……
Sol: create database {Database name}; use uni;

create table student(rollNo int primary key, firstName varchar(25), lastName varchar(20), grade
varchar(3));

create table course(CId varchar(10) primary key, cName varchar(10), duration int
check(duration<6), rollNo int, foreign key(rollNo) references student(rollNo));

create table login(UserId int primary key, password varchar(25), foreign key(UserId) references
student(rollNo));

insert into student values(101, "PRABHJOT", "KAUR", "A");

insert into student values(102, "SALONI", "ARORA", "B+");

insert into student values(103, "MANPREET", "KAUR", "A+");

insert into student values(104, "ESHU", "GUPTA", "A");

insert into student values(105, "KARAN", "SINGH", "B");

insert into course values("1", "SOFTWARE ENGINEERING ", "4", 101);

insert into course values("2", "Computer Science engineering", "4",102);

insert into course values("3", "BSc ", "3", 103);

insert into course values("4", "BCA","3", 104);

insert into course values("5", "MCA", "2", 105);

insert into login values(101, "PRABHJOT101");

insert into login values(102, "SALONI100");

insert into login values(103, "MANPREET222");

insert into login values(104, "ESHU104");

insert into login values(105, "KARAN123");


update login set password ="Riya103" where UserId=103;

update login set password="Nidhi102 " where UserId=102;

update login set password="Mohit " where UserId=105;

Select operations:

Select * from student;

Select * from course;

Select * from login;


TASK -3

Create the tables for the following ER- Diagram:

Put all necessary constraints using the create


command. Ensure that all relations are
established.
Insert at least 5 entries in each table.
Write select command for following conditions:
1. Display order no. of all orders placed by aman or any other customer.
2. Display the name of the customer who placed ordered more then 5 quantities of a given
productno.

• create table CUSTOMER (Customer_ID int primary key,Title varchar(20), First_Name


varchar(20),Last_Name varchar(20),Phone_No int, Address varchar(50), City varchar(20),
State varchar (20),Postal_Code int , Company varchar(20), Rating int);

• insert into CUSTOMER values(001,'Miss','Aastha',null,0987654321,'#12, Roosevelt


Road','Ellenabad','Haryana',127021,'ABC',NULL);

• insert into CUSTOMER values(002,'Mr','Aman','Bhatia',0985554321,'#567, Urban


Estate','Kapurthala','Punjab',144601,'DEF',3);

• inser intoCUSTOMER values(003,'Mrs','Katrina','Kaushal',0987123111,'#123,


South City','Chunmpun','Tamil Nadu',156789,'EFG',NULL);

• insertinto CUSTOMERvalues(004,'Mr','Sham',null,null,'Sainki
Colony','Bandra','Maharashtra',120001,'EFG',5);

• insert into CUSTOMER values(005,'Mr','Gajinder','Modi',0986754321,'Palki


Dhaam','Surat','Gujarat',123561,'ABC',4;

• select * from CUSTOMER;

• create table ORDERS(Order_No int primary key, Customer_ID int ,Date, foreign
key(Customer_ID) references CUSTOMER(Customer_ID));
• insert into ORDERS values(100,001,'12-04-22');
• insert into ORDERS values(101,002,'12-04-22');
• insert into ORDERS values(102,001,'17-05-22');
• insert into ORDERS values(103,003,'22-05-22');
• insert into ORDERS values(104,005,'23-05-22');
• insert into ORDERS values(105,001,'23-05-22');
• insert into ORDERS values(106,004,'24-05-22');
• insert into ORDERS values(107,003,'12-06-22');
• insert into ORDERS values(108,002,'12-06-22');
• insert into ORDERS values(109,004,'12-06-22');

• select * from ORDERS;

• create table STOCKS (Product_No int primary key, Description varchar (255), Catalog
varchar(255), Quantity_in_Pieces int ,Cost_per_unit int, Selling_Price_per_unit int , Order_No
int, foreign key(Order_No) references ORDERS(Order_No));
• insert into STOCKS values(213,'Dove Soap','MFG: 12-02-22 , COLOUR: Green, WEIGHT:
0.5g', 1279,75,75, 108);
• insert into STOCKS values(214,'PUMA Night Wear','MFG: 22-02-21 ,
COLOUR: Pink, Fabric: Cotton', 100,1280,1280, 107);
• insert into STOCKS values(215,'DELL Laptop','MFG: 13-04-21 , COLOUR:Steel Grey,
WEIGHT: 1899g', 7,71280,71280, 102);
• insert into STOCKS values(216,'TUPPERWARE Crockery SET','MFG: 02-01-22
, COLOUR8Green, WEIGHT: 0.5g', 50,279,279, 106);
• insert into STOCKS values(217,'Pears Soap','MFG: 12-12-21 , COLOUR:White, WEIGHT:
0.5g', 12,75,75, 103);
• insert into STOCKS values(218,'SHEENS Saree','MFG: 01-10-21 ,
COLOUR:Red, Fabric: Saturn', 1908,1200,1200, 104);
• insert into STOCKS values(219,'QUARTZ Watch','MFG: 29-08-21 ,
COLOUR:Steel Grey, WEIGHT: 0.5g', 127,2389,2389, 105);
• insert into STOCKS values(210,'AK Mens Wallet','MFG: 12-02-21 ,
COLOUR:Brown, WEIGHT: 0.9g', 279,710,710, 109);
• insert into STOCKS values(211,'MEGH Hair Accessories','MFG: 30-09-20
,
COLOUR:Magenta, WEIGHT: 0.5g', 129,75,75, 100);
• insert into STOCKS values(212,'ABC Hankercheifs','MFG: 17-12-21 , COLOUR: Green,
WEIGHT: 0.5g', 1279,75,75, 101);

• select * from STOCKS;

• create table ORDER_FOR_STOCK (Order_No int,Product_No int,Qty_Order int


, Qty_Ship int,primary key( Order_No ,Product_No));
• insert into ORDER_FOR_STOCK values(100,210,2,2);
• insert into ORDER_FOR_STOCK values(101,211,15,15);
• insert into ORDER_FOR_STOCK values(102,212,85,85);
• insert into ORDER_FOR_STOCK values(103,213,151,5);
• insert into ORDER_FOR_STOCK values(104,214,2,2);
• insert into ORDER_FOR_STOCK values(105,215,1,1);  insert into ORDER_FOR_STOCK
values(106,216,1,1);
• insert into ORDER_FOR_STOCK values(107,217,9,9);
• insert into ORDER_FOR_STOCK values(108,218,1,1);
• insert into ORDER_FOR_STOCK values(109,219,1,1);  select * from
ORDER_FOR_STOCK;
1. Display order no. of all orders placed by aman or any other customer

• select ORDERS.Order_No,CUSTOMER.First_Name from ORDERS, CUSTOMER where


ORDERS.Customer_ID=CUSTOMER.Customer_ID and
CUSTOMER.First_Name = 'Aman' ;

1. Display the name of the customer who placed ordered more then 5 quantities of a given
productno.

• select CUSTOMER.First_Name,ORDERS.Order_No, ORDER_FOR_STOCK.Qty_Order


from
CUSTOMER,ORDERS,ORDER_FOR_STOCK where
CUSTOMER.Customer_ID = ORDERS.Customer_ID and
ORDER_FOR_STOCK.Order_No=ORDERS.Order_No and
ORDER_FOR_STOCK.Qty_Order>5;

1. Display all orders placed between two dates.


• select Order_No from ORDERS where ORDERS.Date between '12-04- 20'and'1206-22';

TASK -4

Write three select commands for the following three


problems:

From the following table rite a sql query to find the salesperson and customer
who live in the same city. Return customer name, salesperson name and
salesperson city.
SOLUTION:

SELECT salesman.name, customer.cust_name, salesman.city FROM


salesman, customer
WHERE salesman.city=customer.city;

From the following table write an sql query to find those customers who served by
salesperson and the salesperson works at the commission in the range
12% to 14% (Begin and end values included). Return cust_name AS
“Customer”, city AS “City”.

SOLUTION:
SELECT customer.cust_name as Customer, customer.city as City, salesman.name
FROM salesman as T1 INNER JOIN customer as T2 ON
T1.salesman_id=T2.salesman_id;

From the following table, write a SQL query to find those customer who made orders
on October 5, 2012. Return customer_id, cust_name, city, grade, salesman_id, ord_no,
purch_amt, ord_date, customer_id and salesman_id.
SOLUTION:
SELECT customer.customer_id, customer.cust_name, customer.city,
customer.grade, customer.salesman_id, orders.ord_no, orders.purch_amt,
orders.ord_date, orders.customer_id, orders.salesman_id
FROM salesman as T1 INNER JOIN orders as T2 ON
T1.salesman_id=T2.salesman_id
WHERE ord_date=’2012-10-5’;

Normalize the relation into different normal forms.Try and reach highest level of
normalization possible.

For example below we have one big table. Put the table in normalized form.
OID=Order ID, O_Date=Order Date,

CID=Customer ID, C_Name=Customer Name, C_State=Customer’s State,


PID=project id, P_Desc=Project Name, P_Price=Product Price, Qty=Quantity Purchased
Note:7, 5, 4 means Product Ids. Similarly, 1, 1, 5 means three Quantities.

Highest Normal Form: 3rd

OID O_Date CID C_Name C_State


1006 10/24/09 2 Apex NC
1006 10/24/09 2 Apex NC
1006 10/24/09 2 Apex NC
1007 10/25/09 6 Acme GA
1007 10/25/09 6 Acme GA

CID PID P_Desc CID PID P_Price


2 7 Table 2 7 800
2 5 Desk 2 5 325
2 4 Chair 2 4 200
6 11 Dresser 6 11 500
6 4 Chair 6 4 200

TASK -5
Consider the following schema for a Library Database:
BOOK (Book_id, Title, Publisher_Name, Pub_Year) BOOK_AUTHORS (Book_id,
Author_Name)
PUBLISHER (Name, Address, Phone)
BOOK_COPIES (Book_id, Branch_id, No-of_Copies)
BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)
LIBRARY_BRANCH (Branch_id, Branch_Name, Address)
1 Write SQL queries to 1. Retrieve details of all books in the library_id, title, name
of publisher, authors, number of copies in each branch, etc .

Sol:
select BOOK.Book_id, BOOK.Title,
BOOK.Publisher_name,BOOK_AUTHOR.Author_Name, BOOK_COPIES.No_of_copies,
LIBRARY_BRANCH.Branch_id from BOOK, BOOK_AUTHORS, BOOK_COPIES,
LIBRARY_BRANCH where
BOOK.Book_id=BOOK_AUTHOR.Book_id and
BOOK.Book_id=BOOK_AUTHOR.Book_id
BOOK.Book_id=BOOK_COPIES.Book_id and
LIBRARY_BRANCH.Branch_id=BOOK_COPIES.Bracnh_id;

2 Get the particulars of borrowers who have borrowed more than three books jan
2018 to jun 2018. Sol:

Select Card_No from BOOK_LENDING where Date_Out between ‘01-JAN- 2018’ and ‘01-
jun-2018’ group by Card_No having count (*)>3;

3. Delete a book in BOOK table. Update the contents of other tables to reflect this
data manipulation operation.

Sol:
Delete from BOOK where Book_id =3;

4. Partition the BOOK table based on year of publication. Demonstrate its working
with a simple query.
Sol:
Create view V_Publication as select Pub_year from BOOK;
5. Create a view of all books and its number of copies that are currently available
in the Library.
Sol:
Create view V_BOOK as select BOOK.Book_id, BOOK.Title, BOOK_COPIES.No_of_copies
from BOOK, BOOK_COPIES, LIBRARY_BRANCH where
BOOK.Book_id=BOOK_COPIES.Book_id and
BOOK_COPIES.Branch_id=LIBRARY_BRANCH.Branch_id;
TASK -6
Consider the following schema for Order Database:
SALESMAN (Salesman_id, Name, City, Commission)
CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
ORDERS (Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)

Write SQL queries to

1. Count the customers with grades above Amritsar’s average

Sol:
SELECT grade, COUNT (*)
FROM customer
GROUP BY grade
HAVING grade > (SELECT AVG(grade)
FROM customer
(WHERE city = 'Amritsar');

2. Find the name and numbers of all salesmen who had more than one customer.
Sol:
SELECT salesman_id,name
FROM salesman a
WHERE 1 < (SELECT COUNT(*)
FROM customer
WHERE salesman_id=a.salesman_id);

3. List all salesmen and indicate those who have and don’t have customers in
their cities (Use UNION operation.)
Sol:
SELECT salesman.salesman_id, name, cust_name, commission
FROM salesman, customer
WHERE salesman.city = customer.city
UNION
(SELECT salesman_id, name, 'NO MATCH', commission
FROM salesman
WHERE NOT city = ANY
(SELECT city
FROM customer))
ORDER BY 2 DESC

4.Create a view that finds the salesman who has the customer with the highest order
of a day.

Sol:
CREATE VIEW elitsalesman
AS SELECT b.ord_date, a.salesman_id, a.name
FROM salesman a, orders b
WHERE a.salesman_id = b.salesman_id
AND b.purch_amt =
(SELECT MAX (purch_amt)
FROM orders c
WHERE c.ord_date = b.ord_date);

5. Demonstrate the DELETE operation by removing salesman with id 1000. All his
orders must also be deleted.
Sol:
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table
orders and then execute the following: Use ON DELETE SET NULL at the end of foreign key
definitions while creating child table customers and then executes the following:
DELETE FROM SALESMAN WHERE SALESMAN_ID=1000;
TASK -7

1) To find sum of two numbers using PL/SQL

declare -- declare
variable x, y -- and z of
datatype number x
number(5); y
number(5); z
number(7);

begin

-- Here we Assigning 10 into x


x:=10;

-- Assigning 20 into x
y:=20;

-- Assigning sum of x and y into z


z:=x+y;

-- Print the Result


dbms_output.put_line('Sum is '||z); end;
/
-- Program End

Output :
Sum is 30

2) To find sum of first 10 natural numbers in PL/SQL


declare
2 i integer;
3 s integer;
4 begin
5 s:=0;
6 for i in 1..10 loop
7 s:=s+i;
8 end loop;
9 dbms_output.put_line('Sum = '||s);
10 end;
11 /
Sum = 55

3) To create a trigger in PL/SQL to convert the name of student in upper case


before insertion

Sql> CREATE TABLE STUDENTS (ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, PRIMARY KEY (ID) );

Sql> CREATE OR REPLACE TRIGGER student_insert_update


2 BEFORE INSERT OR UPDATE ON students
3 FOR EACH ROW
4 DECLARE
5 dup_flag INTEGER;
6 BEGIN
7 --Force all student names to uppercase.
8 :NEW.name := UPPER(:NEW.name);
9 END;
10 /
SQL> INSERT INTO students (id, name) VALUES (1,'aman');

SQL> INSERT INTO students (id, name) VALUES (2,'bhupinder');

Sql> select * from students;

ID Name
1 AMAN
2 BHUPINDER
4) To display number of records updated using rowcount attribute in PL/SQL

DECLARE
i NUMBER;
BEGIN
UPDATE employees
SET status = 'fired'
WHERE name LIKE '%Bloggs';
i := SQL%rowcount;
--note that assignment has to precede COMMIT
COMMIT;
dbms_output.Put_line(i);
END;

5) To create cursor in PL/SQL to increase salary of doctors by 1000

DECLARE
CURSOR cur_emp
IS
SELECT * FROM doctor;
rec_emp cur_emp%rowtype;
BEGIN
OPEN cur_emp;
LOOP
FETCH cur_emp INTO rec_emp;
UPDATE employees
SET salary = salary + 1000
EXIT
WHEN cur_emp%notfound;
END LOOP;
CLOSE cur_emp;
END;
/

6) To display all records of customers table using exception handling


ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
TASK 8

To rename and drop a table

Create students table with ID and NAME and then rename the table to csestudents
Write the command to DROP the csestudents table.

CREATE TABLE STUDENTS (ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, PRIMARY KEY (ID) );
RENAME TABLE STUDENTS TO CSESTUDENTS;
DROP TABLE CSESTUDENTS;
TASK 9
Implement nested query

Consider the following table Students


id name class_id GPA
1 Jack Black 3 3.45
2 Daniel White 1 3.15
3 Kathrine Star 1 3.85
4 Helen Bright 2 3.10
5 Steve May 2 2.40

Write SQL query to display the names of all students who got more then average GPA
Sql> SELECT * FROM students WHERE GPA > (SELECT AVG(GPA) FROM students);
Consider employee table

1. SQL> CREATE TABLE STUDENTS (


2. ID INT NOT NULL,
3. NAME VARCHAR (20) NOT NULL,
4. SALARY INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );

Write SQL command to find 2nd highest salary


SELECT * from Employee
WHERE Salary IN (SELECT MAX(Salary)
FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary)
FFROM employee));

Aggregate Function
TASK -10

Consider the following table


PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Com1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120

Display the count of tuple with rate greater then equal to 20


1. ] SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Display the name of the company and count for that company only if count is greater than 2.
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Find the total cost for all items

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
TASK -11

Like function
Consider the following students table
id name class_id GPA
1 Jack Black 3 3.45
2 Daniel White 1 3.15
3 Kathrine Star 1 3.85
4 Helen Bright 2 3.10
5 Steve May 2 2.40
Write sql statement to display name of all students starting with ‘h’
Sql> SELECT * FROM students
WHERE name LIKE 'a%';
TASK -12

Practical- Join
Consider the following orders and customers table

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Write SQL statement using INNER JOIN that selects records that have matching values in both
tables

Write SQL statement using LEFT JOIN that will select all customers, and any orders they might
have:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM
Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER
BY Customers.CustomerName;
TASK -13
Practical-
To insert value of ID attribute in students table using sequence

CREATE TABLE STUDENTS (ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, PRIMARY KEY (ID) ); CREATE
SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;

CREATE TABLE students


(
ID number(10),
NAME char(20)
);

INSERT into students VALUES(sequence_1.nextval,'Ramesh');


INSERT into students VALUES(sequence_1.nextval,'Suresh');
TASK -14
Practical-
Create a table student and create an index on that table on name attribute

1. SQL> CREATE TABLE STUDENTS (


2. ID INT NOT NULL,
3. NAME VARCHAR (20) NOT NULL,
4. SALARY INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );

CREATE INDEX INDEX_NAME ON STUDENTS (NAME);


task 15 Grant, Revoke command

Create a user and then grant some rights to the user on student table and also revoke some of the
rights granted to user

1. SQL> CREATE TABLE STUDENTS (


2. ID INT NOT NULL,
3. NAME VARCHAR (20) NOT NULL,
4. SALARY INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );

CREATE USER student_admin IDENTIFIED BY admin123;

GRANT CONNECT TO student_admin;

GRANT SELECT, INSERT, UPDATE, DELETE ON students TO student_admin;

REVOKE DELETE ON STUDENTS TO student_admin


Task 16
PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL Code,
Referencing Non-SQL parameters.
PL/SQL Architecture
The PL/SQL is a case insensitive, a robust procedural extension of the SQL. The SQL
allows its statements to be directly included in the PL/SQL blocks and still looks like a
single language together as they are tightly coupled with each other as there are no APIs
needed to bind them together unlike other programming languages.
PLSQL Block Structure
The structure of a PL/SQL block consists of the below four primary sections.
1. Header
2. Declaration
3. Execution
4. Exception

PL/SQL assignments and expressions:-


Write a program that declares an integer variable called num, assigns a value to it, and
computes and inserts into the tempp table the value of the variable itself, its square, and its
cube.

CREATE TABLE tempp ( item number, square number, CUBE number );


TABLE created.
DECLARE num number:=&num;
BEGIN
INSERT INTO tempp VALUES(num,
num*num,
num*num*num);
END;
Enter value FOR num: 5
SELECT * FROM tempp;
OUTPUT:-
ITEM SQUARE CUBE
5 25 125
PL/SQL CODE:-
DECLARE
VAR1 NUMBER;
VAR2 NUMBER;

BEGIN
VAR1:=200;
VAR2:=1;
WHILE (VAR2<=5)
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
VAR2:=VAR2+1;
END LOOP;
END;
OUTPUT:-
200
400
600
800
1000

Parameters Modes:-
IN mode- Default; Passes a constant value from the calling environment to the procedure
Create or replace procedure raise_salary
(p_id IN employees.emp_id%type)
IS
Begin
Update employees set
salary=salary*0.10
where emp_id=p_id
End raise_salary;

OUT Mode- Passes a value from procedure to the calling environment


DECLARE
emp_num NUMBER(6) := 120;
bonus NUMBER(6) := 50;
emp_last_name VARCHAR2(25); PROCEDURE
raise_salary (emp_id IN NUMBER, amount IN
NUMBER,
emp_name OUT VARCHAR2) IS
BEGIN
UPDATE employees SET salary = salary
+ amount WHERE employee_id = emp_id;
SELECT last_name INTO emp_name
FROM employees
WHERE employee_id = emp_id;
END raise_salary;
BEGIN
raise_salary(emp_num, bonus, emp_last_name);
DBMS_OUTPUT.PUT_LINE
('Salary was updated for: ' || emp_last_name);
END;
IN OUT Mode- Passes a constant value from the calling environment to the procedure and a
possibly different value from procedure to the calling environment using the same parameter.
CREATE OR REPLACE PROCEDURE SWAP_TEST AS
A NUMBER := 3;
B NUMBER := 8;
PROCEDURE MY_SWAP(X IN OUT NUMBER,Y IN OUT NUMBER) AS
T NUMBER;
BEGIN
T := X;
X := Y;
Y := T;
END MY_SWAP;
BEGIN
12 MY_SWAP(A,B);
13 DBMS_OUTPUT.PUT_LINE('A = ' || TO_CHAR(A));
14 DBMS_OUTPUT.PUT_LINE('B = ' || TO_CHAR(B));
15 END;
Task 17
Stored Procedures and Exceptional Handling.
Stored Procedures
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more
specific task.
This is similar to a procedure in other programming languages.
SYNTAX:-
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;

CREATE OR REPLACE PROCEDURE employer_details


IS
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl; emp_rec
emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name || ' ' ||emp_cur.salary);
END LOOP;
END;
Exception Handling in PL/SQL

An exception is an error which disrupts the normal flow of program instructions. PL/SQL
provides us the
exception block which raises the exception thus helping the programmer to find out the fault
and resolve it.
There are two types of exceptions defined in PL/SQL
1. User defined exception.
2. System defined exceptions.
Syntax :-
WHEN exception THEN
Statement;
Consider the table STUDENT :-
ID NAME MARKS
1 AKSHAY 100
2 PRAVEEN 97
3 JESSIE 99

DECLARE
temp varchar(20);
BEGIN
SELECT ID into temp from STUDENT where NAME='RAHUL';
exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR:');
dbms_output.put_line('there is no name as');
dbms_output.put_line(' RAHUL in STUDENT table');
end;
OUTPUT:-
ERROR: There is no name as RAHUL in STUDENT table
Task 18
Triggers and Cursor Management in PL/SQL.
1. Triggers:
o A trigger is a stored procedure in the database that is automatically
executed in response to specific events, such as INSERT, UPDATE, or
DELETE on a table.
o Triggers are useful for enforcing business rules, auditing changes, or
maintaining complex integrity constraints.
2. Cursors:
o A cursor is a pointer that allows you to retrieve, manipulate, and iterate
over query results row by row.
o Two types of cursors:
 Implicit Cursor: Created automatically when a SELECT, INSERT,
UPDATE, or DELETE operation is executed.
 Explicit Cursor: Defined explicitly by the programmer for complex
operations.

Steps to Create a Trigger


1. Define the event (BEFORE or AFTER an operation).
2. Specify the operation (INSERT, UPDATE, or DELETE).
3. Write the PL/SQL code block to execute during the event.
Syntax for Trigger:
sql

CREATE OR REPLACE TRIGGER trigger_name


BEFORE|AFTER INSERT|UPDATE|DELETE ON table_name
[FOR EACH ROW]
DECLARE
-- Variable declarations (optional)
BEGIN
-- Trigger logic
END;

Steps to Create a Cursor


1. Declare the cursor and associate it with a query.
2. Open the cursor to allocate memory.
3. Fetch data from the cursor into variables.
4. Close the cursor to release memory.
Syntax for Cursor:
sql

DECLARE
CURSOR cursor_name IS
SELECT column1, column2 FROM table_name;
variable1 table_name.column1%TYPE;
variable2 table_name.column2%TYPE;
BEGIN
OPEN cursor_name;
LOOP
FETCH cursor_name INTO variable1, variable2;
EXIT WHEN cursor_name%NOTFOUND;
-- Process fetched data
END LOOP;
CLOSE cursor_name;
END;

Create trigger to update logs to the EMPLOYEES table into an AUDIT_LOG table.
Tables:
1. EMPLOYEES(emp_id, emp_name, salary)
2. AUDIT_LOG(audit_id, emp_id, old_salary, new_salary, change_date)
Trigger Code:
sql

CREATE OR REPLACE TRIGGER trg_audit_update


AFTER UPDATE OF salary ON EMPLOYEES
FOR EACH ROW
BEGIN
INSERT INTO AUDIT_LOG (audit_id, emp_id, old_salary, new_salary, change_date)
VALUES (audit_seq.NEXTVAL, :OLD.emp_id, :OLD.salary, :NEW.salary,
SYSDATE);
END;

Create a cursor to calculate the average salary from the EMPLOYEES table and logs
employees earning above average into a HIGH_SALARY_EMPLOYEES table.
Tables:
1. EMPLOYEES(emp_id, emp_name, salary)
2. HIGH_SALARY_EMPLOYEES(emp_id, emp_name, salary)
Cursor Code:
sql

DECLARE
CURSOR emp_cursor IS
SELECT emp_id, emp_name, salary FROM EMPLOYEES;
avg_salary NUMBER;
emp_id EMPLOYEES.emp_id%TYPE;
emp_name EMPLOYEES.emp_name%TYPE;
salary EMPLOYEES.salary%TYPE;
BEGIN
-- Calculate average salary
SELECT AVG(salary) INTO avg_salary FROM EMPLOYEES;
-- Process each employee
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_id, emp_name, salary;
EXIT WHEN emp_cursor%NOTFOUND;

-- Insert employees with salary above average


IF salary > avg_salary THEN
INSERT INTO HIGH_SALARY_EMPLOYEES (emp_id, emp_name, salary)
VALUES (emp_id, emp_name, salary);
END IF;
END LOOP;
CLOSE emp_cursor;
END;
38 | P a g e

You might also like