0% found this document useful (0 votes)
8 views40 pages

Dbms Complete

The document outlines various SQL operations for creating and manipulating database tables related to customers, sales, hospitals, bank customers, employees, and products. It includes creating tables, inserting records, altering structures, and executing queries to retrieve specific data. The document provides detailed SQL commands and expected outputs for each operation.

Uploaded by

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

Dbms Complete

The document outlines various SQL operations for creating and manipulating database tables related to customers, sales, hospitals, bank customers, employees, and products. It includes creating tables, inserting records, altering structures, and executing queries to retrieve specific data. The document provides detailed SQL commands and expected outputs for each operation.

Uploaded by

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

1.

Create a table customer (cust_no varchar (5), cust_name varchar (15), age number, phone varchar (10))
a) insert 5 records and display it
b) add new field d_birth with date datatype
c) create another table cust_phone with fields cust_name and phone from customer table
d) remove the field age
e) change the size of the cust_name to 25
f) delete all the records from the table
g) rename the table cutomer to cust
h) drop the table
Queries:
create table customer(cust_no varchar(5),cust_name varchar(15),age int, phone varchar(10));
A) insert into customer values(1,’SHAMEEM’,19,234578);
insert into customer values(2,'ASWIN',19,7865490);
insert into customer values(3,'ATHUL',19,4567321);
insert into customer values(4,'ASWANI',19,5895624);
insert into customer values(5,'ADITHYA',19,895262);
select * from customer;
B) alter table customer add d_birth date;
C). create table cust_phone as select cust_name,phone from customer;
D). alter table customer drop age;
E). alter table customer alter column cust_name type varchar(25);
F). delete from customer;
G). alter table customer rename to cust;
H). drop table cust;
Table structure:-
Customer

Attribute Datatype Constraint

cust_no varchar(5)

cust_name varchar(15)

age number

phone varchar(10)
Cust_phone

Attribute Datatype Constraint

cust_name varchar(15)

phone varchar(10)
Output:

a.)
cust_no | cust_name | age | phone
---------+-----------+-----+---------
1 | SHAMEEM | 19 | 234578
2 | ASWIN | 19 | 7865490
3 | ATHUL | 19 | 4567321
4 | ASWANI | 19 | 5895624
5 | ADITHYA | 19 | 895262

b.) ALTER TABLE


select *from customer;
cust_no | cust_name | age | phone | d_birth
---------+-----------+-----+---------+---------
1 | SHAMEEM | 19 | 234578 |
2 | ASWIN | 19 | 7865490 |
3 | ATHUL | 19 | 4567321 |
4 | ASWANI | 19 | 5895624 |
5 | ADITHYA | 19 | 895262 |
c.) SELECT 5
select *from cust_phone;
cust_name | phone
-----------+---------
SHAMEEM | 234578
ASWIN | 7865490
ATHUL | 4567321
ASWANI | 5895624
ADITHYA | 895262
(5 rows)
d.) DROP TABLE
e.) ALTER TABLE
f.) DELETE 5
g.)ALTER TABLE
h.) DROP TABLE

2. Create a table sale_man (salesman_no primary key, s_name not null, place, phone unique)

Create table sales_order (order_no primary key order_date not null salesman_no foreign key references
salesman_no in sales_man del_type values should be either P or F (check constraints) order_status values should be
'Inprocess','Fullfilled','Backorder', 'Cancelled' (checkconstraints))

a) Insert few records in both tables


b) Delete primary key from sales_man table
c) Delete Foreign key and Check constraints from sales_order table
d) Add primary key in sales_man using ALTER TABLE
e) Add foreign key and CHECK constraints in sales_order table using ALTER TABLE

Queries:
create table salesman(salesman_no varchar(5)primary key,s_name varchar(10) not null,place varchar(15),phone
varchar(15) unique);
create table sales_order(order_no varchar(5) primary key,order_date date not null,salesman_no varchar(5) references
salesman,del_type char check(del_type in ('p','f')),order_status varchar(15) check(order_status in
('inprocess','fulfilled','backorder','cancelled')));
a.) insert into salesman values('S01','Rijas','Mumbai','9784563214');
insert into salesman values('S08','Pranoy','Pune','6589632145');
insert into sales_order values('OD01','12-02-2019','S01','p','inprocess');

insert into sales_order values('OD02','03-05-2019','S08','f','cancelled');

c.)alter table sales_order drop constraint sales_order_salesman_no_fkey;


alter table sales_order drop constraint sales_order_del_type_check;
alter table sales_order drop constraint sales_order_order_status_check;
b.)alter table salesman drop constraint salesman_pkey;
d.)alter table salesman add primary key (salesman_no);
e.)alter table sales_order add foreign key (salesman_no) references salesman(salesman_no);
alter table sales_order add constraint del_type check(del_type in('p','f'));
alter table sales_order add constraint order_status check(order_status
in('inprocess','fulfilled','backorder','cancelled'));

Table Structure:

\d salesman;

\d sales_order;
Select*from salesman;

Select*from sales_order;

A). 2 rows inserted, 2 rows inserted


C.)Alter Table
B.) Alter Table
D.) Alter Table
E.) Alter Table

3.) Create a table Hospital with the fields (doctorid,doctorname,department,qualification,experience).


Write the queries to perform the following.
a) Insert 5 records
b) Display the details of Doctors
c) Display the details of doctors who have the qualification ‘MD’
d) Display all doctors who have more than 5 years experience but do not have the qualification ‘MD’
e) Display the doctors in ‘Skin’ department
f) update the experience of doctor with doctored=’D003’ to 5
g) Delete the doctor with DoctorID=’D005’
Queries:
create table hospital(doctorid varchar(5), doctorname char(10),department char(10), qualification
varchar(10), experience varchar(5));

A.) insert into hospital values('d001','Arun','Skin','MBBS','9');


insert into hospital values('d002','Athira','Ortho','MD','3');
insert into hospital values('d003','Kavya','Skin','MD','7');
insert into hospital values('d004','Kiran','ENT','BHMS','5');
insert into hospital values('d005','Jaya','Gynac','MBBS','8');
B). select * from hospital;
C). select * from hospital where qualification='MD';
D). select doctorname from hospital where experience>'5' and qualification!='MD';
E). select doctorname from hospital where department='Skin';
F). update hospital set experience='5' where doctorid='d003';
G). delete from hospital where doctorid='d005';

Table Structure

Output:-

Table created.
a). 5 rows inserted.
b).
doctorid doctorname department qualification experience

d001 Arun Skin MBBS 9

d002 Athira Ortho MD 3

d003 Kavya Skin MD 7

d004 Kiran ENT BHMS 5

d005 Jaya Gynac MBBS 8

c).
doctorid doctorname department qualification experience

D002 Athira Ortho MD 3

D003 Kavya Skin MD 7

d).
doctorname

Arun

Jaya

e).
doctorname

Arun

Kavya

f.) UPDATE 1

g.) DELETE 1
4.) Create the following tables
Bank_customer (accno primary key, cust_name, place)
Deposit (accno foreign key, deposit_no, damount)
Loan (accno foreign key loan_no, Lamount)
Write the following queries
a) Display the details of the customers
b) Display the customers along with deposit amount who have only deposit with the bank
c) Display the customers along with loan amount who have only loan with the bank
d) Display the customers they have both loan and deposit with the bank
e) Display the customer who have neither a loan nor a deposit with the bank

Query:-
create table bank_customer(acc_no int primary key, cust_name varchar(10), place varchar(15));
create table deposit (acc_no int references bank_customer(acc_no), deposit_no int,damount int);
create table loan(acc_no int references bank_customer(acc_no), loan_no int, l_amount int);

insert into bank_customer values(12344,'Abin','Kannur');


insert into bank_customer values(12345,'Arun','Kozhikode');
insert into bank_customer values(12346,'Athira','Koyilandi');
insert into bank_customer values(12347,'Samuel','Manjeri');
insert into bank_customer values(12348,'Aparna','Aluva');
insert into bank_customer values(12349,'Kiran','Pattambi');

insert into deposit values(12345,100,25000);


insert into deposit values(12346,101,30000);
insert into deposit values(12347,102,300000);

insert into loan values(12345,200,70000);


insert into loan values(12348,201,65000);
insert into loan values(12349,202,35000);

A). select b.acc_no,b.cust_name,b.place,d.deposit_no,d.damount,l.loan_no,l.l_amount from bank_customer b full


join deposit d on (b.acc_no=d.acc_no) full join loan l on(b.acc_no=l.acc_no);

B). select cust_name,damount from bank_customer,deposit where bank_customer.acc_no=deposit.acc_no and not


exists(select * from loan where loan.acc_no=bank_customer.acc_no);

C). select cust_name,l_amount from bank_customer,loan where bank_customer.acc_no=loan.acc_no and not


exists(select * from deposit where deposit.acc_no=bank_customer.acc_no);

D). select cust_name from bank_customer,deposit,loan where bank_customer.acc_no=loan.acc_no and


bank_customer.acc_no=deposit.acc_no;

E). select cust_name from bank_customer where acc_no not in(select acc_no from deposit union select acc_no
from loan);

Table Structure:
\d bank_customer;
\d loan;

\d deposit;

a.)

b.)

c.)
d.)

e.)

5. Create a table employee with fields (EmpID, EName, Salary, Department, and Age). Insert some records. Write
SQL queries using aggregate functions and group by clause
A. Display the total number of employees.
B. Display the name and age of the oldest employee of each department.
C. Display the average age of employees of each department
D. Display departments and the average salaries
E. Display the lowest salary in employee table
F. Display the number of employees working in purchase department
G. Display the highest salary in sales department;
H. Display the difference between highest and lowest salary

Query:-
create table employee(emp_id int, emp_name varchar(10), salary float, department varchar(10), age float);

insert into employee values(101,'JOSEPH',25000,'Sales',30);


insert into employee values(102,'STEPHEN',30000,'Sales',37);
insert into employee values(103,'DAVID',18000,'Sales',21);
insert into employee values(104,'JOHN',15000,'Marketing',25);
insert into employee values(105,'JAMES',21000,'Purchasing',32);
insert into employee values(106,'KARTHIK',25000,'Purchasing',35);
A). select count(*) from employee;
B). select emp_name,department,age from employee where age in(select max(age) from employee group by
department);
C). select department,avg(age) from employee group by department;
D). select department,avg(salary) from employee group by department;
E). select min(salary) from employee;
F). select count(*) from employee where department='Purchasing';
G). select max(salary) from employee where department=’Sales’;
H). select max(salary)-min(salary) as salary_difference from employee;

Table Structure

Output:-
Table created.
6 rows inserted.
a).

count(*)

b).
emp_name department age

STEPHEN Sales 37

JOHN Marketing 25

KARTHIK Purchasing 35
c).
department avg(age)

Purchasing 33.5

Sales 29.33

Marketing 25

d).
department avg(salary)

Purchasing 23000

Sales 24333.33

Marketing 15000

e).
min(salary)

15000

f).
count(*)

g).
max(salary)

30000

h).
salary_difference

15000

6. Create a table product with the fields (Product_code primary key, Product_Name, Category, Quantity, Price).
Insert some records Write the queries to perform the following.
a. Display the records in the descending order of Product_Name
b. Display Product_Code, Product_Name with price between 20 and 50
c. Display the details of products which belongs to the categories of ‘bath soap’, ‘paste’, or ‘washing powder’
d. Display the products whose Quantity less than 100 or greater than 500
e. Display the products whose names starts with 's'
f. Display the products which not belongs to the category 'paste'
g. Display the products whose second letter is 'u' and belongs to the Category 'washing powder'

Query:-
create table product(product_code varchar(4) primary key,product_name char(10),category char(20),
quantity int,price int);
insert into product values('p111','Dove','Bathsoap',600,38);
insert into product values('p112','Sunlight','Washing powder',200,65);
insert into product values('p113','Chandrika','Handwash',500,20);
insert into product values('p114','Santoor','Bathsoap',100,30);
insert into product values('p115','Ariel','Washing powder',60,10);
insert into product values('p116','Colgate','Paste',120,25);
insert into product values('p117','Closeup','Paste',150,35);
insert into product values('p118','Sandal','Bathsoap',650,80);
insert into product values('p119','Gathri','Washing powder',100,30);
insert into product values('p120','Kabani','Washing soap',650,70);

A). select * from product order by product_name desc;


B). select product_code,product_name from product where price between 20 and 50;
C). select * from product where category in('Bathsoap','Washing powder','Paste');
D). select * from product where (quantity<100 or quantity>500);
E). select product_name from product where product_name like 'S%';
F). select product_name from product where category <>'Paste';
G). select product_name from product where product_name like '_u%' and category='Washing powder';
Table Structure:

Output:-
Table created.
10 rows
inserted.a).

b).
product_co product_name
de
p111 Dove

p113 Chandrika

p114 Santoor

p116 Colgate

p117 Closeup

p119 Gathri
c).
product_cod product_nam category quanitity price
e e
p111 Dove Bathsoap 600 38

p112 Sunlight Washing 200 65


powder
p114 Santoor Bathsoap 100 30

p115 Ariel Washing 60 10


powder
p116 Colgate Paste 120 25

p117 Closeup Paste 150 35

p118 Sandal Bathsoap 650 80

p119 Gathri Washing 100 30


powder

d).
product_code product_n category quantity price
a me
p111 Dove Bathsoap 600 38

p115 Ariel Washingpowder 60 10

p118 Sandal Bathsoap 650 80

p120 kabani Washingsoap 650 70

e).
product_nam
e
Sunlight

Santoor

Sandal
f).
product_nam
e
Dove

Sunlight

Chandrika

Santoor

Ariel

Sandal

Gathri

Kabani

g).
product_name

sunlight

7. Consider the employee database given below. Give an expression in SQL for each of the following queries:
EMPLOYEE (Employee-Name, City)
WORKS (Employee-Name, Company-Name, Salary)
COMPANY (Company-Name, City)
MANAGES (Employee-Name, Manager-Name)
A) Find the names of all employees who work in Infosys
B) Find the names and cities of residence of all employees who works in Wipro
C) Find the names, and cities of all employees who work in Infosys and earn
more than Rs. 10,000.
D) Find the employees who live in the same cities as the companies for which
they work.
E) Find all employees who do not work in Wipro Corporation.
F) Find the company that has the most employees.
Query:-
create table employee(emp_name varchar(20),city varchar(20));
create table works(emp_name varchar(20),company_name varchar(20),salary int); create table
company(company_name varchar(20),city varchar(20));
create table manages(emp_name varchar(20),manager_name varchar(20));

insert into employee values('Ajith','Tirur');


insert into employee values('Alex','Tanur');
insert into employee values('Shahina','Manjeri');
insert into employee values('Sindhu','Calicut');
insert into employee values('Balan','Vadakara');

insert into works values('Ajith','Infosys',25000);


insert into works values('Alex','TCS',35000);
insert into works values('Shahina','Wipro',20000);
insert into works values('Sindhu','Infosys',10000);
insert into works values('Balan','Infosys',15000);
insert into company values('Infosys','Calicut');
insert into company values('Wipro','Trivandrum');
insert into company values('TCS','Kochi');
insert into manages values('Ajith','Sachin');
insert into manages values('Alex','Sayooj');
insert into manages values('Shahina','Akhila');
insert into manages values('Sindhu','Kiran');
insert into manages values('Balan','Salman');

A). select emp_name from works where company_name='Infosys';


B). select employee.emp_name,employee.city from employee,works where
employee.emp_name=works.emp_name and works.company_name='Wipro';
C). select employee.emp_name,employee.city from employee,works where
employee.emp_name=works.emp_name and works.company_name='Infosys' and salary>10000;
D). select employee.emp_name from employee,company where employee.city=company.city;

E). select emp_name from works where company_name!='Wipro';


F). select company_name,count(*) as no_of_employees from works group by company_name having
count(distinct emp_name)>=all(select count(distinct emp_name) from works group by company_name);
Table structure:-
Employee
Attribute Datatype Constraints

emp_name varchar(20)

city varchar(20)

Works
Attribute Datatype Constraints

emp_name varchar(20)

company_name varchar(20)

salary number

Company
Attribute Datatype constraints

company_name varchar(20)

city varchar(20)

Manages
Attributes Datatype Constraints

emp_name varchar(20)

manager_name varchar(20)

Output:-
Table created.
Table created.
Table created.
Table created.
a).
emp_name

Ajith

Sindhu

Balan

b).
emp_name city

Shahina Manjeri

c).
emp_name city

Ajith Tirur

Balan Vadakara

d).
emp_name

Sindhu

e).
emp_nam
e

Ajith

Alex

Sindhu

Balan
f).
company_name no_of_employees

Infosys 3

8. Create table supplier(supcode,sname,city)


Create table product (pcode,pname)
Create table supl_product(supcode,pcode,qty)
a) Get all pairs of supplier numbers such that the two suppliers are located in the same city.
b) Get supplier names for suppliers who supply product P2.
c) Get product numbers supplied by more than one supplier.
d) Get supplier numbers for suppliers who are located in the same city as supplier S1.
e) Get supplier names for suppliers who supply part P1.
f) Get the number of Suppliers, who are supplying at least one product.
g) For each product supplied, get the pcode. and the total quantity supplied for that part.

Queries:
create table product(pcode varchar(3)primary key,pname varchar(30));
create table supplier(supcode varchar(3)primary key,sname varchar(30),city varchar(30));
create table supl_product(supcode varchar(3),pcode varchar(3),qty int);
insert into supplier values('s1','akhil','palakkad');
insert into supplier values('s2','amal','thrissur');
insert into supplier values('s3','raju','palakkad');
insert into supplier values('s4','thomas','malapuram');
insert into product values('p1','colgate');
insert into product values('p2','colgate');
insert into product values('p3','closeup');
insert into product values('p4','sensodine');
insert into supl_product values('s1','p1','50');
insert into supl_product values('s2','p2','25');
insert into supl_product values('s3','p3','25');
insert into supl_product values('s4','p4','50');
insert into supl_product values('s5','p4','50');
a) select f.sname as supplier1 ,s.sname as supplier2 from supplier f,supplier s where f.city=s.city and
f.supcode<>s.supcode;

b.) select sname from supplier ,supl_product where supl_product.pcode='p2' and


supl_product.supcode=supplier.supcode;
c.) select count (supl_product.pcode)from supl_product group by supl_product.pcode having
count(supl_product.supcode)>1;
d.) select supcode from supplier where city=(select city from supplier where supcode='s1');
e) select supplier .sname from supplier,supl_product where supl_product.supcode =supplier .supcode and
supl_product.pcode='p1';
f.)select supplier .supcode from supplier where supplier.supcode in (select distinct supcode from supl_product);
g.) select pcode ,qty from supl_product;
Table structure:
Product:

Supplier

supl_product

output:
a.)
supplier1 | supplier2
-----------+-----------
akhil | raju
raju | akhil

b.) sname
-------
amal
c.)
count
-------
2
d.) supcode
---------
s1
s3
e.) sname
-------
akhil
f.) supcode
---------
s1
s2
s3
s4
g.) pcode | qty
-------+-----
p1 50
p2 25
p3 25
p4 50
p4 50

9.) Prepare a salary report of the employees showing the details such as:
EmpNo, Name, Basic Pay, DA, Gross Salary, PF, Net Salary, Annual Salary and Tax For this purpose,
create a table named SALARIES having the following structure.
Enter the records of at least 10 employees. Use the following information for
calculating the details for the report:
DA is fixed as the 40% of the basic pay.
PF is fixed as 10% of the basic pay.
Gross Salary is (Basic Pay + DA).
Net Salary is (Gross Salary – PF)
Annual Salary is (12 * Net Salary)
Tax is calculated using the following rules:
If annual salary is less than 100000, No Tax
If annual salary is greater than 100000 but less than or equal to 150000, then the tax is 10% of the excess over
100000.
If annual salary is greater than 150000 but less than or equal to 250000, then the tax is 20% of the excess over
150000.
If annual salary is greater than 250000, then the tax is 30% of the excess over 250000.

Queries:

create table salaries (empno varchar(20)primary key,ename varchar(10),basic numeric);


insert into salaries values('11','nisha',1000000);
insert into salaries values ('12','mini',1500000);
create or replace function empsal()
returns void as $$
declare
da numeric;
gsal numeric;
nsal numeric;
asal numeric;
name varchar(10);
pf numeric;
empno varchar(10);
t numeric;
bs numeric;
curl cursor for select *from salaries;
begin
open curl;
loop
fetch curl into empno,name,bs;
exit when not found;
da:=bs*0.4;
pf:=bs*0.1;
gsal:=bs+da;
nsal:=gsal-pf;
asal:=nsal*12;
if (asal<100000)then t:=0;
elsif(asal>100000 and asal<=150000)
then
t:= (asal-100000)*0.1;
elsif(asal>150000 and asal<=250000)
then
t:=(asal-100000)*0.1+(asal-150000)*0.2;
else
t:=(asal-100000)*0.1+(asal-150000)*0.2+(asal-250000)*0.3;
end if;
raise notice'eno=%',empno;
raise notice'ename=%',name;
raise notice'basicsalary=%',bs;
raise notice'da=%',da;
raise notice'pf=%',pf;
raise notice 'gross=%',pf;
raise notice 'net salary=%',nsal;
raise notice 'annal salary=%',asal;
raise notice 'tax=%',t;
end loop;
close curl;
end$$language plpgsql;

Table Structure:

Output:

SELECT empsal();
NOTICE: eno=11
NOTICE: ename=nisha
NOTICE: basicsalary=1000000
NOTICE: da=400000.0
NOTICE: pf=100000.0
NOTICE: gross=100000.0
NOTICE: net salary=1300000.0
NOTICE: annal salary=15600000.0
NOTICE: tax=9245000.00
NOTICE: eno=12
NOTICE: ename=mini
NOTICE: basicsalary=1500000
NOTICE: da=600000.0
NOTICE: pf=150000.0
NOTICE: gross=150000.0
NOTICE: net salary=1950000.0
NOTICE: annal salary=23400000.0
NOTICE: tax=13925000.00

10.) Create table exam_result(rollno, avg_score, Grade) insert 10 records. Assign null values to the field grade.
Write Program block to update the grade field by using the following condition.
avg_score between 90 and 100 - A
avg_score 75 -89 - B
avg_score 60- 74 - C
avg_score 50 -59 - D
avg_score below 50 – E

Queries:

create table exam (rno int primary key,avgscore int,grade varchar(1) null);
insert into exam values(1,75,NULL);
insert into exam values(2,82,NULL);
select *from exam;
create or replace function ExamResult()returns void as $$
declare
G varchar(1);
curl cursor for select rno,avgscore from exam;
Rno int;
avgS int;
begin
open curl;
loop
fetch curl into Rno,avgS;
exit when not found;
if avgS>=90 and avgS<=100
then
G:='A';
elsif avgS>=75 and avgS<=89
then
G:='B';
elsif avgS>=60 and avgS<=74
then
G:='C';
elsif avgS>=50 and avgS<=59
then
G:='D';
else
G:='E';
end if;
update exam set grade=G ;
end loop;
close curl;
end $$ language plpgsql;
Table Structure:

Output:

select ExamResult();

select*from exam;
11.) Write a program code to calculate the area of a circle for a value of radius varying from 3 to 7. Store the radius
and the corresponding value of calculated area in an empty table named areas with field’s radius and area.

Queries:

create table areaa(radius int,area numeric);


create or replace function Rad()
returns void as $$
declare
r int;
a numeric;
begin
for r in 3..7
loop
a:=3.14*r*r;
insert into areaa values(r,a);
end loop;
end $$ language plpgsql;
select * from Rad();
select * from areaa;

Table structure:

Output:
select * from Rad();
select * from areaa;

radius area

3 28.26

4 50.24

5 78.5

6 113.04

7 153.86
12.) .Write a program block to calculate the electricity bill by accepting cust_no and units_consumed
Query:-
create table bill(cons_no int primary key,units int,amount float);
create or replace function elecbill(int,int) returns void
language plpgsql
as $$
declare
cons_no alias for $1;
units alias for $2;
amount float;
begin
amount:=units*6.40;
insert into bill values(cons_no,units,amount);
end;
$$;

Table Structure:

Attribute Datatype Constraint

cons_no int Primary key

units int

amount float

select elecbill(123,216);
select * from bill;

Output:-
Table created.

cons_no units amount

123 216 1382.4


13.) Create a procedure to print Fibonacci number up to a limit, limit is passed as an argument

Query:

create or replace function fib(limt int)


returns void as $$
declare
i int;
t1 int :=0;
t2 int :=1;
t3 int :=0;
begin
raise notice ’ %’ , t1;
raise notice ’%’ , t2;
for i in 2.. limt loop
t3:=t1+t2;
t1:=t2;
t2:=t3;
raise notice ’%’,t3;
end loop;
end $$ language plpgsql;

Output:
select fib(5);
NOTICE: 0
NOTICE: 1
NOTICE: 1
NOTICE: 2
NOTICE: 3
NOTICE: 5

14.) Create a function to check whether a given number is prime or not

QUERY
create or replace function prime (n int)
returns void as $$
declare
i int;
f int:=0;
begin
if n=2 then
f:=0;
else
for i in 2..(n-1)
loop
if(mod (n,i)=0)then
f:=1;
exit;
end if;
end loop;
end if;
if (f=0)then
raise notice 'prime number';
else
raise notice'not prime';
end if;
end $$ language plpgsql;

output:
select prime(5);
NOTICE: prime number

select prime(6);
NOTICE: not prime

15.) create a table stud_mark(regno, sname ,avg_mark)


Insert few records
Write a procedure to display number of students got Distinction, first-class, second class, third class or
failed (90-100 distinction, 75-89 firstclass 60-74 second class 50-59 Third class below 50 failed)

Queries:
create table stud_mark(rno int primary key,sname varchar(10),avg_mark numeric);
insert into stud_mark values(1,'amal',73);
insert into stud_mark values(2,'john',85);
insert into stud_mark values(3,'vishnu',70);
insert into stud_mark values(4,'hari'90);
insert into stud_mark values(5,'athul',55);
select *from stud_mark;
create or replace function mark()returns void as $$
declare
d int:=0;
fc int:=0;
sc int:=0;
tc int:=0;
f int:=0;
curl cursor for select avg_mark from stud_mark;
av int;
begin
open curl;
loop
fetch curl into av;
exit when not found;
if(av>=90 and av<=100)
then
d:=d+1;
elsif(av>=75 and av<=89)
then
fc:=fc+1;
elsif(av>=60 and av<=74)
then
sc:=sc+1;
elsif(av>=50 and av<=59)
then
tc:=tc+1;
else
f:=f+1;
end if;
end loop;
close curl;
raise notice'distinction=%',d;
raise notice 'first class=%',fc;
raise notice'second class=%',sc;
raise notice'third class =%',tc;
raise notice 'failed =%',f;
end $$ language plpgsql;

Table Structure:
16.) .create a table emp_salary(empno,enamedept,salary) Write a function to return the average salary of a particular
department by accepting departmentname as argument.
Queries:
create table empsal(eno int primary key,ename varchar(10), dpt varchar(10),sal int);
insert into empsal values (1, 'Anu', 'sales',10000);
insert into empsal values (2, 'Roy', 'production',20000);
insert into empsal values (3, 'John', 'sales',15000);
select *from empsal;
create or replace function salcal(d varchar)
returns numeric as $$
declare
av numeric;
cur1 cursor for select avg(sal)from empsal where dpt=d;
begin
open cur1;
fetch cur1 into av;
return av;
end $$ language plpgsql;
Table Structure:
\d empsal;

select *from empsal;


eno | ename | dpt | sal
-----+-------+------------+-------
1 | Anu | sales | 10000
2 | Roy | production | 20000
3 | John | sales | 15000
Output

select salcal('sales');
salcal
------------------------
12500.0000000000000000

17.) create a table Student (regno, sname, sub1, sub2, sub3, sub4, sub5, mark_total,avg_mark) Create a BEFORE
INSERT trigger to calculate total mark and average mark and update the corresponding columns.

QUERY
create table student(rno int primary key,snmae varchar(10),S1 int,S2 int,S3 int,S4 int,S5 int,tot int,avg numeric);

create trigger t7 before insert on student for each row


execute procedure mc4();
create or replace function mc4()
returns trigger as $$
begin
NEW.TOT=new.S1+NEW.S2+NEW.S3+NEW.S4+NEW.S5;
NEW.Avg=(NEW.S1+NEW.S2+NEW.S3+NEW.S4+NEW.S5)/5;
return NEW;
end $$language plpgsql;

Table Structure:

OUTPUT
select *from student;
rno | snmae | s1 | s2 | s3 | s4 | s5 | tot | avg
-----+-------+----+----+----+----+----+-----+-----
18.) create table phonebook (pname, mobno) Create a Trigger to insert the old records from
the table phonebook to del_phonebook (pname, mobno, modfy_date) whenever a record is
deleted or updated in the phonebook table

QUERY:

create table phonebook(name varchar primary key,mbno varchar(10));


create table del_phbook(dname varchar(10),del_phno varchar(10),del_date varchar(10));
insert into phonebook values('nimi','9020906');
create or replace function pf()returns trigger as $$
begin
insert into del_phbook values(OLD.name,OLD.mbno,now()::date);
return NEW;
end$$language plpgsql;
create trigger phonetrigger after delete or update on phonebook for each row
execute procedure pf();

TABLE STRUCTURE

\d phonebook;
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
name | character varying | | not null |
mbno | character varying(10) | | |

\d del_phbook;

Column | Type | Collation | Nullable | Default


----------+-----------------------+-----------+----------+---------
dname | character varying(10) | | |
del_phno | character varying(10) | | |
del_date | character varying(10) | | |

output:

select*from phonebook;
name | mbno
------+---------
nimi | 9020906
(1 row)

select*from del_phbook;
dname | del_phno | del_date
-------+----------+----------
(0 rows)
delete from phonebook where name='nimi';
DELETE 1
select*from phonebook;
name | mbno
------+------
(0 rows)

select *from del_phbook;


dname | del_phno | del_date
-------+----------+------------
nimi | 9020906 | 2023-04-21
(1 row)

insert into phonebook values('akhil','901234355');


INSERT 0 1
update phonebook set mbno='8021324435' where name='akhil';
UPDATE 1

select *from del_phbook;


dname | del_phno | del_date
-------+-----------+------------
nimi | 9020906 | 2023-04-21
akhil | 901234355 | 2023-04-21
(2 rows)

select*from phonebook;
name | mbno
-------+------------
akhil | 8021324435
(1 row)

You might also like