0% found this document useful (0 votes)
21 views43 pages

Mistu ADBMS Lab File

Uploaded by

jackoggyduniya
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)
21 views43 pages

Mistu ADBMS Lab File

Uploaded by

jackoggyduniya
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/ 43

DELHI TECHNOLOGICAL UNIVERSITY

(Formerly Delhi College of Engineering) Shahbad


Daulatpur, Bawana Road, Delhi-110042

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

Advanced Database Management Systems Lab File


Subject code: CSE

Submitted To: Submitted By:

Prof Shailendra Kumar Mistu Mahajabin


Department of Computer M.Tech CSE IST Year (Sem-1)
Science and Engineering Roll No. 2K22/CSE/ 27

1
INDEX

Sno. Topic Date Signature


1 Write a program to create table (ER Diagram to
relation)
2 Write a program to implement Integrity constraints

3 Write a program to implement operators in SQL

4 Write a program to implement aggregate functions


in SQL

5 Write a program to implement strings and numeric


functions
6 Write a program to implement Joins

7 Write a program to implement subqueries and


correlated queries

8 Write a program to implement VIEW and WITH


clause

9 Write a program to implement indexing

10 Write a program to study PL/SQL

2
Program 1

OBJECTIVE: Creating tables in PostgreSQL and add tuples in the tables

THEORY:
PostgreSQL is a powerful, open source object-relational database system. It has more than 15
years of active development phase and a proven architecture that has earned it a strong reputation
for reliability, data integrity, and correctness.
This tutorial will give you a quick start with PostgreSQL and make you comfortable with
PostgreSQL programming.
Key Features of PostgreSQL
PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX,
SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It supports text, images, sounds, and video,
and includes programming interfaces for C / C++, Java, Perl, Python, Ruby, Tcl and Open
Database Connectivity (ODBC).
PostgreSQL supports a large part of the SQL standard and offers many modern features including
the following −
 Complex SQL queries
 SQL Sub-selects
 Foreign keys
 Trigger
 Views
 Transactions
 Multiversion concurrency control (MVCC)
You can check official documentation of PostgreSQL to understand the above-mentioned features.
PostgreSQL can be extended by the user in many ways. For example by adding new −
 Data types
 Functions
 Operators
 Aggregate functions
 Index methods
(Theory adopted from https://www.tutorialspoint.com/postgresql)

To create a new table, we use the CREATE TABLE statement:


CREATE TABLE table_name (
column1 datatype(length) column_contraint,
column2 datatype(length) column_contraint,
table_constraints
);
The INSERT statement allows you to insert a new row into a table.
INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …);
3
ER diagrams:

4
CODE:
Create Table Bus(
busno varchar(10) PRIMARY KEY,
src varchar(20),
dest varchar(20),
coach varchar(20)
);

Create Table Reservation(


pnr numeric(9),
jdate date,
5
nseat int,
address varchar(250),
contact_no numeric(10) check(contact_no > 999999999),
busno varchar(10),
seatno int,
PRIMARY KEY(pnr),
FOREIGN KEY(busno) REFERENCES Bus(busno)
);

Create Table Ticket(


tno numeric(9),
jdate date,
age integer,
sex char(10),
src varchar(10),
dest varchar(10),
deptime varchar(10),
busno varchar(10),
PRIMARY KEY(tno),
FOREIGN KEY (busno) REFERENCES Bus(busno)
);

Create Table Passenger(


pnr numeric(9),
tno numeric(9),
pass_name varchar(15),
age integer,
sex char(10),
contact_no numeric(10) check(contact_no>999999999),
PRIMARY KEY(pnr),
FOREIGN KEY(tno) REFERENCES Ticket(tno)
);

Create Table Cancellation(


pnr numeric(9),
jdate date,
seatno integer,
contact_no numeric(10) check(contact_no>999999999),
FOREIGN KEY(pnr) REFERENCES Reservation(pnr)
6
);

INSERT INTO Bus (busno,coach,dest,src)


VALUES
('DL8CZ2457','AC sleeper','Chandigarh','Delhi'), ('CH9DP8723',' sleeper','Delhi','Chandigrh'),
('BH4SK4598','AC sleeper','Patna','Delhi'), ('DL8CZ8756','AC sleeper','Delhi','Ambala'),
('R7LP4590','AC sleeper','Jaipur','Delhi'), ('DL1CZ2345',' sleeper','Meerut','Delhi'),
('UP6AN6591','AC sleeper','Agra','Delhi'), ('KA2QJ5678','sleeper','Bangalore','Mysore'),
('JK3AS7612','AC sleeper','Srinagar','Jammu'), ('PB6TC5489','AC sleeper','Delhi','Amritsar');

INSERT INTO Ticket(tno,jdate,age, sex, src, dest, deptime,busno)


VALUES
(1,'2022-08-23',23,'M','Chandigarh','Delhi','15:30','DL8CZ2457'),
(2,'2022-08-24',52,'M','Patna','Delhi','12:45','BH4SK4598'),
(3,'2022-09-16',28,'F','Bangalore','Mysore','11:00','KA2QJ5678'),
(4,'2022-10-17',23,'F','Delhi','Ambala','15:30','DL8CZ8756'),
(5,'2022-08-22',23,'M','Chandigarh','Delhi','15:30','DL8CZ2457'),
(6,'2022-11-06',72,'F','Chandigarh','Delhi','15:30','DL8CZ2457'),
(7,'2022-09-12',48,'M','Jaipur','Delhi','09:20','R7LP4590'),
(8,'2023-01-01',08,'M','Meerut','Delhi','05:40','DL1CZ2345'),
(9,'2022-01-01',43,'F','Meerut','Delhi','05:40','DL1CZ2345'),
(10,'2023-06-07',33,'M','Agra','Delhi','15:30','UP6AN6591');

INSERT INTO Passenger(pnr,tno,pass_name,age,sex,contact_no)


VALUES
(1286527,1,'Alex',23,'M',7073862138), (1287594,2,'Bob',52,'M',9685021312),
(1325214,3,'Jenny',28,'F',6205879477),(1100527,4,'Ruby',23,'F',7893876139),
(1487564,5,'Blooby',23,'M',8685029911),(1325984,6,'Kiara',72,'F',8794788253),
(1297599,7,'Jack',48,'M', 7483636238),(2147144,8,'Andrew',08,'M',9108502139),
(1782334,9,'Lucifer',43,'F',6605879438),(1542874,10,'Smith',33,'M',9885099312);

INSERT INTO Reservation(pnr, jdate, nseat, address, contact_no, busno, seatno)


VALUES
(1286527, '2022-08-23', 1, 'Rohini Sector-14', 7073862138, 'DL8CZ2457', 23),
(1287594, '2022-08-24', 1, 'Paharganj, New Delhi', 9685021312, 'BH4SK4598', 2),
(1325214, '2022-09-16', 1, 'Old Delhi', 6205879477, 'DL8CZ2457', 11),
(1100527, '2022-10-17', 1, 'Hauz Khaz Village', 7893876139, 'DL8CZ8756', 27),
(1487564, '2022-10-17', 1, 'Samaypur Badli', 8685029911, 'DL8CZ2457', 5),
(1325984, '2022-08-24', 1, 'Rohini Sector-7', 8794788253, 'PB6TC5489', 10),
7
(1297599, '2022-09-12', 1, 'Connaught Place', 7483636238, 'BH4SK4598', 1),
(2147144, '2023-06-07', 1, 'Rohini Sector-18,19', 9108502139, 'JK3AS7612', 8),
(1782334, '2022-09-12', 1, 'ISBT Bus Terminal', 6605879438, 'BH4SK4598', 13),
(1542874, '2022-08-23', 1, 'Lajpat Nagar', 9885099312, 'CH9DP8723', 22),
(2276187, '2022-07-18', 1, 'GTB Nagar', 8800287108, 'CH9DP8723', 21),
(4381287, '2022-07-20', 1, 'Gurgaon Sector-29', 7011234598, 'DL1CZ2345', 12),
(7634214, '2022-08-01', 1, 'Noida Sector-38', 6789556124, 'KA2QJ5678', 30),
(1127647, '2022-09-27', 1, 'Okhla Phase-3', 9312663765, 'PB6TC5489', 3);

INSERT INTO Cancellation(pnr,jdate,seatno,contact_no)


VALUES
(1286527,'2022-08-23',23,7073862138), (1287594,'2022-08-24',2,9685021312),
(1325214,'2022-09-16',11,6205879477), (1100527,'2022-10-17',27,7893876139),
(1487564,'2022-10-17',5,8685029911), (1325984,'2022-08-24',10,8794788253),
(1297599,'2022-09-12',1,7483636238), (2147144,'2023-06-07',8,9108502139),
(1782334,'2022-09-12',13,6605879438), (1542874,'2022-08-23',22,9885099312);

-- Q1
select DISTINCT(pnr) from passenger;

-- Q2
select pass_name from passenger
where sex='M';

-- Q3
select tno, pass_name from passenger;
-- Q5
select tno from passenger
where pass_name similar to 'S%h|s%h|s%H|s%H';

select tno from passenger


where pass_name like 'S%h';

-- Q6
select pass_name from passenger
where age>20 and age<40;

8
OUTPUT:

9
10
LEARNING OUTCOMES:
Learned how to create tables in PostgreSQL and inserting data maintaining integrity constraint

11
Program 2
Adding Integrity Constraints
OBJECTIVE: To add integrity constraints to tables in PostgreSQL.

THEORY:
Integrity constraints can be added during the creation of the table, or after the tables have been
created.
Adding integrity constraints during CREATE TABLE have been shown in the previous program.
Here, consider the tables did not have any integrity constraints. In this case, we have to alter the
definition of the table for which ALTER TABLE is used.

ALTER TABLE — change the definition of a table


To add a primary key,
ALTER TABLE tablename
ADD PRIMARY KEY (column_name);

To add foreign key,


ALTER TABLE child_table
ADD CONSTRAINT constraint_name FOREIGN KEY (c1) REFERENCES parent_table (p1);

To add CHECK constraint,


ALTER TABLE TABLE _name
ADD CONSTRAINT constaint_name CHECK (CONSTRAINT);

CODE:
ALTER TABLE Bus

ADD PRIMARY KEY (busno);

ALTER TABLE Reservation

ADD PRIMARY KEY (pnr);

ALTER TABLE Ticket

ADD PRIMARY KEY (tno);

ALTER TABLE Passenger

ADD PRIMARY KEY (pnr);

12
ALTER TABLE Reservation

ADD FOREIGN KEY (busno) REFERENCES Bus(busno);

ALTER TABLE Ticket

ADD FOREIGN KEY (busno) REFERENCES Bus(busno);

ALTER TABLE Passenger

ADD FOREIGN KEY (tno) REFERENCES Ticket(tno);

ALTER TABLE Cancellation

ADD FOREIGN KEY (pnr) REFERENCES Reservation(pnr);

ALTER TABLE Reservation

ADD CONSTRAINT contact_no CHECK (contact_no>999999999);

ALTER TABLE Passenger

ADD CONSTRAINT contact_no CHECK (contact_no>999999999);

ALTER TABLE Cancellation

ADD CONSTRAINT contact_no CHECK (contact_no>999999999);

OUTPUT:

LEARNING OUTCOMES:
Learned how to add various integrity constraints to already created tables in PostgreSQL.

13
Program 3
Operators in SQL
OBJECTIVE: To learn and implement different types of operators in SQL.

THEORY:

Arithmetic Operators:

(+) : Addition - Adds values on either side of the operator .


(-):Subtraction - Subtracts right hand operand from left hand operand .
(*):Multiplication - Multiplies values on either side of the operator .
(/):Division - Divides left hand operand by right hand operand .
(^):Power- raise to power of .
(%):Modulus - Divides left hand operand by right hand operand and returns remainder.

OUTPUT:

14
Logical Operators:

AND : The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.
OR: The OR operator is used to combine multiple conditions in an SQL statement's WHERE
clause.
NOT: The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

Outputs:

Comparison Operators:
(=):Checks if the values of two operands are equal or not, if yes then condition becomes true.
(!=):Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(< >):Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(>):Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true
(<):Checks if the value of left operand is less than the value of right operand, if yes then
15
condition becomes true.
(>=):Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.
(<=):Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.

OUTPUT:

16
Special Operators:
BETWEEN: The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
IS NULL: The NULL operator is used to compare a value with a NULL attribute value.
ALL: The ALL operator is used to compare a value to all values in another value set
ANY: The ANY operator is used to compare a value to any applicable value in the list
according to the condition.
LIKE: The LIKE operator is used to compare a value to similar values using wildcard
operators.It allows to use percent sign(%) and underscore ( _ ) to match a given string pattern.
IN: The IN operator is used to compare a value to a list of literal values that have been
specified.
EXIST: The EXISTS operator is used to search for the presence of a row in a specified table
that meets certain criteria.

OUTPUT:

17
LEARNING OUTCOME:
Implementation and use of different types of oprators in SQL were successfully studied.

18
Program 4

OBJECTIVE: Practice Queries using Aggregate functions, Group By, Having Clause and
Order Clause.

THEORY:
Aggregate functions compute a single result from a set of input values
1) Avg (Average): This function will return the average of values of the column specified in
the argument of the column.
2) Min(expression): minimum value of expression across all non-null input values
3) Max(expression): maximum value of expression across all non-null input values
4) Sum(expression): sum of expression across all non-null input values
5) Count(expression): number of input rows for which the value of expression is not null
6) The GROUP BY clause divides the rows returned from the SELECT statement into
groups. For each group, you can apply an aggregate function e.g., SUM() to calculate the sum of
items or COUNT() to get the number of items in the groups.
7) The HAVING clause specifies a search condition for a group or an aggregate. The
HAVING clause is often used with the GROUP BY clause to filter groups or aggregates based
on a specified condition.

CODE:
Create Table Employee(
emp_ID numeric(9),
emp_name varchar(15),
dept_name varchar(15),
dept_no numeric(1),
salary numeric(15),
PRIMARY KEY(emp_ID)
);

-- Production 1, Testing 2, Management 3, Marketing 4


INSERT INTO Employee (emp_ID, emp_name, dept_name, dept_no, salary)
VALUES
(1, 'John', 'Production', 1, 1200000),
(2, 'Adam', 'Testing', 2, 1000000),
(3, 'Sandra', 'Management', 3, 1500000),
(4, 'Tony', 'Testing', 2, 1000000),
(5, 'Cassandra', 'Production', 1, 1300000),
(6, 'Daisy', 'Marketing', 4, 1000000),
(7, 'Josh', 'Marketing', 4, 1600000),
19
(8, 'Aman', 'Production', 1, 1300000),
(9, 'Vance', 'Testing', 2, 2500000),
(10, 'Ashley', 'Management', 3, 1950000);

-- Average
select avg(salary) from Employee;

-- Minimum
select min(salary) from Employee;

-- Maximum
select max(salary) from Employee;

-- Sum
select sum(salary) as total_cost_to_company from Employee;

-- Count
select count(*) from Employee;
select count(distinct dept_no) from Employee;

-- Group by
select dept_no,count(*) from Employee
group by dept_no
order by dept_no;

-- Having
select dept_no,avg(salary) from Employee
group by dept_no
having dept_no=1 or dept_no=2;

OUTPUT:

20
21
LEARNING OUTCOMES:
Learned how to use aggregate functions in PostgreSQL.

22
Program 5

OBJECTIVE: Practice Queries using String and Numeric functions in PostgreSQL

THEORY:
Strings in this context include values of the types character, character varying, and text.
The string functions used in this program as described as follows:
1) Initcap (Expression): This String function is used to capitalize first character of the input
string.
2) Lower(Expression): The LOWER function takes in value with either all uppercase or
partial uppercase values or characters and convert them into lower case.
3) Upper(Expression): The UPPER function takes in value with either all lowercase or
partial lowercase values or characters and convert them into uppercase.
4) RPAD/LPAD: lpad()/rpad() function is used to fill up a string of specific length by a
substring.
5) BTRIM: remove the longest string specified in the argument from the start and end of a
given string.

CODE:
DROP TABLE IF EXISTS Student;

Create Table Student(


stud_name varchar(50),
stud_ID varchar(10) PRIMARY KEY,
course varchar(20),
fee numeric(9),
faculty_name varchar(50),
last_4_aadhar varchar(20)
);

INSERT INTO Student (stud_name, stud_ID, course, fee, faculty_name, last_4_aadhar)


VALUES
('Adam','CSE01','CSE', 1200000, 'Shailendra Kumar', 8173),
('Aman','CSE02','CSE', 1300000, 'Shailendra Kumar', 1172),
('Akanksha','MTH01','MATH', 850000, 'Rajendra Verma', 1233),
('Raj','MTH02','MATH', 850000, 'Rajendra Verma', 4172),
('Riya','CHEM01','CHEM', 900000, 'Archana Rani', 9137),
('karan','CHEM02','CHEM', 900000, 'Archana Rani', 2100),
('eshita','PHY01','PHY', 1000500, 'Rinku Sharma', 7672),
23
('sagar','PHY02','PHY', 1000500, 'Rinku Sharma', 9128);

-- Q1 Capitalize all student's first name


update student set stud_name= INITCAP (stud_name);

-- Q2 Convert all course names to lower case


update student set course = LOWER(course);

-- Q3 Convert all faculty names to upper case


update student set faculty_name = UPPER(faculty_name);

-- Q4 Convert all course name=’math’ to maths, ‘phy’ to physics, ‘chem’ to chemistry


update student set course = 'maths' where course='math';
update student set course = 'physics' where course='phy';
update student set course = 'chemistry' where course='chem';

-- Q5 Pad all aadhar numbers with 4 * on left and right


update student set last_4_aadhar = RPAD(LPAD(last_4_aadhar, 8, '*'), 12, '*');

-- Q6 Trim all * from aadhar


update student set last_4_aadhar = BTRIM(last_4_aadhar,'*');

-- Q7 Length of all student names starting with 'A'


select stud_name, length(stud_name) as length_of_name from Student
where stud_name LIKE 'A%';
-- Q8 Concatenate 'Prof. ' in front of each faculty name
update Student set faculty_name = CONCAT('Prof. ', faculty_name);

-- Q9 Demontrating ceil/floor
select course,avg(fee) as avg_fee, ceil(avg(fee)) as ceil_val, floor(avg(fee))as floor_val
from Student group by course;

-- Q10 Demonstrating mod


select fee, Mod(fee,100) from Student;

OUTPUT:

24
25
26
27
LEARNING OUTCOMES:
Learned how to use string and numeric functions in PostgreSQL

Program 6

OBJECTIVE: Practice Joins in PostgreSQL

THEORY:
The PostgreSQL Joins clause is used to combine records from two or more tables in a database.
A JOIN is a means for combining fields from two tables by using values common to each.
CROSS JOIN matches every row of the first table with every row of the second table.
INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate.
OUTER JOIN is an extension of the INNER JOIN. SQL standard defines three types of OUTER
JOINs: LEFT, RIGHT, and FULL and PostgreSQL supports all of these.

CODE:
DROP TABLE IF EXISTS order_master, order_detail;
Create Table order_master(
order_no varchar(20) PRIMARY KEY,
item_name varchar(50),
rate_per_item numeric(10),
qty_available INTEGER
);

28
Create Table order_detail(
client_ID varchar(20) PRIMARY KEY,
order_no varchar(20),
qty_reqd INTEGER,
FOREIGN KEY(order_no) REFERENCES order_master(order_no)
);

INSERT INTO order_master (order_no, item_name, rate_per_item, qty_available)


VALUES
('A01','Headlights','350', 100), ('A02','Disk Brake','550', 150), ('A03','Battery','1350',
50),
('A04','Oil Filter','120', 300), ('A05','Body Side Moulding','2400',70),
('A06','Windshield Wiper','400', 83);

INSERT INTO order_detail(client_ID, order_no, qty_reqd)


VALUES
('C01','A01', 10), ('C02','A03', 8), ('C03','A05', 200), ('C05','A02', 80),
('C07','A01', 11), ('C08','A03', 1), ('C09','A01', 20), ('C10','A03', 2),
('C11','A05', 9), ('C12','A04', 121), ('C13','A04', 28);

-- Inner Join/Natural Join with Condition


select a.*, b.* from order_master a, order_detail b
where a.qty_available< b.qty_reqd
and a.order_no = b.order_no;

-- Cross Join
SELECT * from order_master CROSS JOIN order_detail;

-- Left Outer
select * from order_master LEFT OUTER JOIN order_detail
on order_master.order_no = order_detail.order_no;

-- Right Outer
select * from order_master RIGHT OUTER JOIN order_detail
on order_master.order_no = order_detail.order_no;

29
OUTPUT:

30
31
LEARNING OUTCOMES:
Learned how to use joins in PostgreSQL

Program 7
Subqueries And Correlated Queries

OBJECTIVE: To learn and implement subqueries and correlated queries on a database.

THEORY:

Subqueries
Subqueries are enclosed in parentheses. Subquery is also called an inner query and the query
which encloses that inner query is called an outer query. Many times subqueries can be replaced
with joins.

select * from Employee where DepartmentID not in (select distinct DepartmentID from
Department)

32
Columns present in subqueries cannot be used in the outer select list of a query.

Correlated Subqueries

If the subquery depends on the outer query for its value then it is called a Correlated Subquery.
Correlated subqueries are executed for every single row executed by outer subqueries.

A correlated subquery can be executed independently,

select distinct Department_Name,(select count(*) from Employee where


DepartmentID=d.DepartmentID group by Depar

CODE:

SQL> select * from order_detail where order_no = (select order_no from order_master where
order_no = 'A01');

OUTPUT:

SQL> select * from order_master where order_no in (select order_no from order_detail);

SQL>Select * from order_master where order_no = any(select order_no from order_detail);

33
Correlated Queries:
SQL> select * from order_master as o where exists (select order_no from order_detail where
order_no = o.order_no);

OUTPUT:

SQL> select * from order_master as o where not exists (select order_no from order_detail where
order_no = o.order_no);

LEARNING OUTCOME:
Implementation and use of subqueries and correlated queries on a database were successfully
studied.

34
Program 8

OBJECTIVE: Practice Views and With clause in PostgreSQL

THEORY:
Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinary tables
to SELECT. A view can represent a subset of a real table, selecting certain columns or certain
rows from an ordinary table. A view can even represent joined tables. Because views are
assigned separate permissions, you can use them to restrict table access so that the users see only
specific rows or columns of a table.
A view can contain all rows of a table or selected rows from one or more tables. A view can be
created from one or many tables, which depends on the written PostgreSQL query to create a
view.

CODE:
DROP TABLE IF EXISTS Employee, Dept;

Create Table Dept(


dept_no numeric(1) PRIMARY KEY,
manager_name varchar(15)
);

Create Table Employee(


emp_ID numeric(9),
emp_name varchar(15),
dept_name varchar(15),
dept_no numeric(1),
salary numeric(15),
PRIMARY KEY(emp_ID),
FOREIGN KEY (dept_no) REFERENCES Dept(dept_no)
);

-- Production 1, Testing 2, Management 3, Marketing 4


INSERT INTO Dept (dept_no, manager_name)
VALUES

35
(1, 'Ms. Vidya'), (2, 'Mr. Abhishek'), (3, 'Ms. Nitya'), (4, 'Mr. Abhimanyu');

INSERT INTO Employee (emp_ID, emp_name, dept_name, dept_no, salary)


VALUES
(1, 'John', 'Production', 1, 1200000), (2, 'Adam', 'Testing', 2, 1000000),
(3, 'Sandra', 'Management', 3, 1500000), (4, 'Tony', 'Testing', 2, 1000000),
(5, 'Cassandra', 'Production', 1, 1300000), (6, 'Daisy', 'Marketing', 4, 1000000),
(7, 'Josh', 'Marketing', 4, 1600000), (8, 'Aman', 'Production', 1, 1300000),
(9, 'Vance', 'Testing', 2, 2500000), (10, 'Ashley', 'Management', 3, 1950000);

-- Creating a View
Create View EmpView As Select * from Employee;
Select emp_ID,emp_name,salary from EmpView where dept_no in(2,3);

-- Updatable View
Create View Emp_vw As
Select emp_ID, emp_name, dept_no from Employee;

Insert into Emp_vw values(11,'Bob',4);


Delete from Emp_vw where emp_ID=11;

-- View defined from Multiple tables


Create View EmpDept_Vw As
Select a.emp_ID,a.emp_name,a.salary,a.dept_no,b.manager_name From Employee a,Dept b
Where a.dept_no=b.dept_no;

WITH with_test AS ( Select emp_ID, emp_name, dept_no FROM Employee)


Select dept_no, count(*)
From with_test group by dept_no;

OUTPUT:

36
37
LEARNING OUTCOMES:
Learned how to use VIEW and WITH clause in PostgreSQL

38
Program 9
Index
OBJECTIVE: To learn and implement use of indexes on a database.

THEORY:

An index is an ordered list of the contents of a column, (or a group of columns) of a table.
It is used to retrieve data from a database very fast. Indexing a table or view is, one of the best
ways to improve the performance of queries and applications.

It is a quick lookup table for finding records users need to search frequently. An index is small,
fast, and optimized for quick lookups. It is very useful for connecting relational tables and
searching large tables.

CODE:

Simple Index:

Syntax:
Create Index <Index Name> On <Table Name>(ColumnName);

Query:
SQL>Create Index idx_order_no On order_master (order_no) ;

OUTPUT:

Creating Composite Index:

Syntax:
Create Index <Index Name> On <Table Name>(ColumnName, ColumnName);

Query:
SQL>Create Index idx_order_no_and_item_name On order_master (order_no, item_name) ;

OUTPUT:

39
Creation of Unique Index:

Syntax:
Create Unique Index <Index Name> On <Table Name> (ColumnName,ColumnName);

Query:
SQL>Create Unique Index unq_idx_order_no On order_master (order_no) ;

OUTPUT:

Dropping Indexes:

Syntax:
Drop Index <Index Name>;

Query:
SQL>Drop Index idx_order_no;

OUTPUT:

LEARNING OUTCOME:
Implementation and use of indexes on a database was successfully studied.

40
Program 10
PL/SQL
OBJECTIVE: Write a program by the use of PL/SQL.

THEORY:

The PL/SQL programming language was developed by Oracle Corporation in the late
1980s as procedural extension language for SQL and the Oracle relational database. PL/SQL has
the following features-
● PL/SQL is tightly integrated with SQL.
● It offers extensive error checking.
● It offers numerous data types.
● It offers a variety of programming structures.
● It supports structured programming through functions and procedures.
● It supports object-oriented programming.
● It supports the development of web applications and server pages.

Query 1:

DECLARE
a number (2) := 21;
b number (2) := 10;
BEGIN
IF (a = b) then
RAISE NOTICE 'Line 1 - a is equal to b';
ELSE
RAISE NOTICE 'Line 1 - a is not equal to b';
END IF;
IF (a < b) then
RAISE NOTICE 'Line 2 - a is less than b';
ELSE
RAISE NOTICE 'Line 2 - a is not less than b';
END IF;
IF ( a> b ) THEN
RAISE NOTICE 'Line 3 - a is greater than b';
ELSE
RAISE NOTICE 'Line 3 - a is not greater than b';
END IF;
END;
/

OUTPUT:
Line 1 - a is not equal to b
41
Line 2 - a is not less than b
Line 3 - a is greater than b

Query 2:

Write a pl/sql program To insert two entries into the emp table.

Begin
Insert into emp(empno,ename) values(100,’Shruti’);
Insert into emp(empno,ename) values(101,’Yesha’);
End;
/
OUTPUT:

Query 3 :

Write a pl/sql program To get the area of the circle provided the radius is given.

DO
$$
--Find the area and perimeter of circle
DECLARE

-- Variables to store area and perimeter


area NUMERIC (6, 2) ;
perimeter NUMERIC(6, 2) ;

--Assigning the value of radius


radius NUMERIC(1) := 3;

--Constant value of PI
pi CONSTANT NUMERIC(3, 2) := 3.14;

BEGIN
--Formula for area and perimeter of a circle
area := pi * radius * radius;
perimeter := 2 * pi * radius;
RAISE NOTICE 'Area = %', area;
RAISE NOTICE ' Perimeter = %', perimeter;

END;
$$

OUTPUT:
42
LEARNING OUTCOME:
Implementation and use of PL/SQL was successfully studied.

43

You might also like