Mistu ADBMS Lab File
Mistu ADBMS Lab File
1
INDEX
2
Program 1
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)
4
CODE:
Create Table Bus(
busno varchar(10) PRIMARY KEY,
src varchar(20),
dest varchar(20),
coach varchar(20)
);
-- 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';
-- 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.
CODE:
ALTER TABLE Bus
12
ALTER TABLE Reservation
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:
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)
);
-- 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
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;
-- 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;
OUTPUT:
24
25
26
27
LEARNING OUTCOMES:
Learned how to use string and numeric functions in PostgreSQL
Program 6
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)
);
-- 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
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.
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);
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
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;
35
(1, 'Ms. Vidya'), (2, 'Mr. Abhishek'), (3, 'Ms. Nitya'), (4, 'Mr. Abhimanyu');
-- 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;
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:
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
--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