You are on page 1of 34

Advance Database Management System LAB

ETCS - 457

Faculty name: Prof. Savita Student Name: Manvi Tyagi

Enrl. No.: 41714802717

Semester: 7th

Maharaja Agrasen Institute of Technology, PSP Area, Sector – 22,


Rohini, New Delhi – 110085
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

VISION
To nurture young minds in a learning environment of high academic value and imbibe spiritual and ethical
values with technological and management competence.

MISSION
The Institute shall endeavor to incorporate the following basic missions in the teaching
methodology: ​Engineering Hardware – Software Symbiosis
Practical exercises in all Engineering and Management disciplines shall be carried out by Hardware
equipment as well as the related software enabling deeper understanding of basic concepts and encouraging
inquisitive nature.
Life – Long Learning
The Institute strives to match technological advancements and encourage students to keep updating their
knowledge for enhancing their skills and inculcating their habit of continuous learning.
Liberalization and Globalization
The Institute endeavors to enhance technical and management skills of students so that they are
intellectually capable and competent professionals with Industrial Aptitude to face the challenges of
globalization.
Diversification
The Engineering, Technology and Management disciplines have diverse fields of studies with different
attributes. The aim is to create a synergy of the above attributes by encouraging analytical thinking.
Digitization of Learning Processes
The Institute provides seamless opportunities for innovative learning in all Engineering and Management
disciplines through digitization of learning processes using analysis, synthesis, simulation, graphics, tutorials
and related tools to create a platform for multi-disciplinary approach.
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by enhancing their skills and research
capabilities so that they become successful entrepreneurs and responsible citizens.

MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

COMPUTER SCIENCE & ENGINEERING DEPARTMENT


VISION
To Produce “Critical thinkers of Innovative Technology”

MISSION
To provide an excellent learning environment across the computer science discipline to
inculcate professional behaviour, strong ethical values, innovative research capabilities and
leadership abilities which enable them to become successful entrepreneurs in this globalized
world.

1. To nurture an ​excellent learning environment ​that helps students to enhance their


problem solving skills and to prepare students to be lifelong learners by offering a solid
theoretical foundation with applied computing experiences and educating them about
their ​professional, and ethical responsibilities​.
2. To establish ​Industry-Institute Interaction​, making students ready for the industrial
environment and be successful in their professional lives.
3. To promote ​research activities ​in the emerging areas of technology convergence.
4. To build engineers who can look into technical aspects of an engineering solution thereby
setting a ground for producing successful ​entrepreneur.
Index
Exp. Experiment Name Date of Marks Signature
no checking

Write a brief
note on
PostGreSQl.
List the
features of
PostGreSQL
and its
installation
steps.

Comparison of various Databases


with Postgre SQL

Data Definition Language


Commands

Data Manipulation Language,


&In-Built Functions

​Nested Subqueries and joins.

Views

Procedure & Function

​Trigger
Experiment 1
Aim: ​Write a brief note on PostGreSQl. List the features of PostGreSQL and its
installation steps.
Theory:
PostgreSQL is a general purpose and object-relational database management system, the most
advanced open source database system. PostgreSQL was developed based onPOSTGRES 4.2
atBerkeleyComputerScienceDepartment​, ​University of California.

PostgreSQL was designed to run on UNIX-like platforms. However, PostgreSQL is designed to be


portable so that it could run on various platforms such as Mac OS X, Solaris, and Windows.

Discuss the PostgreSQL features on the following guidelines:

• User-defined types
• Table inheritance
• Sophisticated locking mechanism
• Foreign key referential integrity
• Views, rules, subquery
• Nested transactions (savepoints)
• Multi-version concurrency control (MVCC)
• Asynchronous replication

Installation Steps:

Follow the given steps to install PostgreSQL on the Linux machine. Make sure we are logged in as
root before we proceed for the installation.

Select postgresql-9.2.4-1-linux-x64.run for the desired machine.

Now, let us execute it as follows:


[root@host]#chmod +x postgresql-9.2.4-1-linux-x64.run

[root@host]# ./postgresql-9.2.4-1-linux-x64.run

------------------------------------------------------------------------ Welcome to the PostgreSQL Setup

Wizard.

------------------------------------------------------------------------ Please specify the directory where

PostgreSQL will be installed.

Installation Directory [/opt/PostgreSQL/9.2]:

Once we launch the installer, it will ask a few basic questions like location of the installation,
password of the user who will use database, port number, etc. So keep all of them at their default
values except password, which we can provide as per our choice. It will install PostgreSQL at our
Linux machine and will display the following message:
Please wait while Setup installs PostgreSQL on our computer.

Installing

0% ______________ 50% ______________ 100% #########################################

----------------------------------------------------------------------- Setup has finished installing PostgreSQL on our computer.

Follow the following post-installation steps to create your database −


[root@host]#su - postgres

Password: bash-4.1$

createdbtestdb bash-4.1$

psqltestdbpsql (8.4.13,

server 9.2.4)

test=#

we can start/restart postgres server in case it is not running using the following command −
[root@host]# service postgresql restart

Stopping postgresql service: [ OK ]

Starting postgresql service: [ OK ]

If our installation is correct, we will have PotsgreSQL prompt ​test=# ​as shown above.
Viva - Questions: Built-in Functions
Q1. What is the default value stored in an attribute when a tuple is inserted with missing value in the corresponding
attribute? Explain.

Ans 1. ​The default value is set to Null as keeping it blank or using a garbage value might lead to some improper function or
procedure to trigger.

Q2. What the different string functions that we use in postgreSql.


Ans 2. ​List of String Functions
a. Concatenation
b. Bit Length
c. Char Length
d. Byte Length
e. Convert to Lowercase
f. Convert to Uppercase
g. Replace substring
h. Substring
Q3. What is the difference between delete, drop and truncate command?
Ans 3. Delete vs Drop vs Truncate
1. DELETE :
Basically, it is a Data Manipulation Language Command (DML). It is used to delete the one or more tuples of a table. With the
help of the “DELETE” command we can either delete all the rows in one go or can delete row one by one. i.e., we can use it as
per the requirement or the condition using Where clause. It is comparatively slower than TRUNCATE cmd.
2. DROP :
It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the help of the “DROP” command
we can drop (delete) the whole structure in one go i.e. it removes the named elements of the schema. By using this command
the existence of the whole table is finished or lost.
3. TRUNCATE :
It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table) in one go. With the
help of the “TRUNCATE” command we can’t delete the single row as here WHERE clause is not used. By using this command
the existence of all the rows of the table is lost. It is comparatively faster than delete command as it deletes all the rows fastly.

Q4. Why do we use the Limit function?


Ans 4. ​The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the
number of records returned based on a limit value.
Experiment 2
AIM: ​Comparison of various Databases with Postgre SQL
PostgreSQL MySQL

Known as The world’s most ​advanced The world’s most ​popular ​open
open source database source database

GUI tool PgAdmin MySQL Workbench

Storage engine Single ​storage engine Multiple ​storage engines e.g.,


InnoDB and MyISAM

Programming Ruby, Perl, Python, TCL, SQL:2003 syntax for ​stored procedures
languages for ​stored PL/pgSQL, SQL, JavaScript,
procedures etc.

Full Outer Join Yes No

Partial indexes Yes No

Bitmap indexes Yes No

Expression indexes Yes No

Triggers Support triggers that can fire Limited to some commands


on most types of command,
except for ones affecting the
database globally e.g., roles
and
tablespaces.

Partitioning RANGE, LIST RANGE, LIST, HASH, KEY, and


composite partitioning using a
combination of RANGE or LIST with
HASH or KEY subpartitions

Task Schedule pgAgent Scheduled event

PostgreSQL MongoDB

ACID Transactions ACID Transactions

Table Collection

Row Document

Column Field

Secondary Index Secondary Index

JOINs Embedded documents, $lookup & $graphLookup


GROUP_BY Aggregation Pipeline

Name MariaDB PostgreSQL

Description MySQL application compatible open source Widely used open source RDBMS
RDBMS, enhanced with high availability,
security, interoperability and performance
capabilities. With MariaDB ColumnStore a
column-oriented storage engine is available
too.

Secondary Document store Document store


database Graph DBMS Key-value store

models Key-value store

Developer MariaDB Corporation Ab (MariaDB PostgreSQL Global


Enterprise), MariaDB Foundation Development Group
(community MariaDB Server)

Implementati C and C++ C


on language

Server FreeBSDLinuxSolarisWindows FreeBSDHP


operating UXLinuxNetBSDOpenBSDOS
systems XSolarisUnixWindows

Supported AdaCC#C++DEiffelErlangGoHaskellJavaJava .NetCC++DelphiJavaPerlPHPPytho


programmi Script n
ng (Node.js)Objective-COCamlPerlPHPPythonRu
languages by

Server-side yes user defined functions


scripts

Partitioning Horizontal partitioning, sharding with declarative partitioning (by range


methods Spider storage engine or Galera cluster or by list) since PostgreSQL 10.0

Replication Master-master replication Master-slave replication


methods Master-slave replication

In-memory yes no
capabilities
Viva - Questions: postgreSQL

Q1. What are the different platforms PostgreSQL support?

Ans1. ​PostgreSQL can work on these operating systems:


1. Linux (all recent distributions),
2. Windows (Win2000 SP4 and later),
3. FreeBSD, OpenBSD, NetBSD, Mac OS X, AIX, HP/UX, IRIX, Solaris, Tru64 Unix, and UnixWare. Other Unix-like
systems may also work but are not currently being tested.
Q2. Compare PostgreSQL with other DBMSs?
Ans2.

Name MongoDB MySQL PostgreSQL

Description One of the most Widely used open Widely used open
popular document source RDBMS source RDBMS
stores available both
as a fully managed
cloud service and
for deployment on
self-managed
infrastructure

Developer MongoDB, Inc Oracle PostgreSQL Global


Development Group

Initial 2009 1995 1989


release

Current 4.4.2, November 8.0.22, 2020 13.1, November 2020


release 2020

License Open Source Open Source Open Source

Implementat C++ C and C++ C


ion language

Server Linux FreeBSD FreeBSD


operating OS X Linux HP-UX
systems
Solaris OS X Linux
Windows Solaris NetBSD
Windows OpenBSD
OS X
Solaris
Unix
Windows

Data scheme schema-free yes yes

SQL Read-only SQL yes yes


queries via the
MongoDB
Connector for BI

Server-side JavaScript yes user defined


scripts functions

Partitioning Sharding horizontal partitioning by range,


methods partitioning, sharding list and (since
with MySQL Cluster PostgreSQL 11) by
or MySQL Fabric hash

Replication Multi-Source Multi-source Source-replica


methods deployments with replication replication
MongoDB Atlas Source-replica
Global Clusters replication
Source-replica
replication

MapReduce yes no no

Foreign no yes yes


keys

Q3. List features of PostgreSQL.


Ans 3. ​Feature of Postgres
1. User-defined types
2. Table inheritance
3. Sophisticated locking mechanism
4. Foreign key referential integrity
5. Views, rules, subquery
6. Nested transactions (savepoints)
7. Multi-version concurrency control (MVCC)
8. Asynchronous replication

Q4. What are the key differences between MySQL and PostgreSQL? Which Open Source Database to Choose and
Why?

Name MySQL PostgreSQL

Description Widely used open source RDBMS Widely used open source RDBMS

Developer Oracle PostgreSQL Global Development


Group

Initial release 1995 1989


Current 8.0.22, 2020 13.1, November 2020
release

License Open Source Open Source

Implementatio C and C++ C


n language

Server FreeBSD FreeBSD


operating Linux HP-UX
systems
OS X Linux
Solaris NetBSD
Windows OpenBSD
OS X
Solaris
Unix
Windows

Data scheme yes yes

SQL yes yes

Server-side yes user defined functions


scripts

Partitioning horizontal partitioning, sharding with partitioning by range, list and (since
methods MySQL Cluster or MySQL Fabric PostgreSQL 11) by hash

Replication Multi-source replication Source-replica replication


methods Source-replica replication

MapReduce no no

Foreign keys yes yes

Q5. List a few limitations of PostgreSQL.

Ans 5. ​Limitations of PostgreSQL.


1. The length of each lexeme must be less than 2K bytes
2. The length of a ​tsvector​ (lexemes + positions) must be less than 1 megabyte
3. The number of lexemes must be less than 264
4. Position values in ​tsvector​ must be greater than 0 and no more than 16,383
5. The match distance in a ​<​N​>​ (FOLLOWED BY) ​tsquery​ operator cannot be more than 16,384
6. No more than 256 positions per lexeme
7. The number of nodes (lexemes + operators) in a ​tsquery​ must be less than 32,768
Experiment 3

Aim​: ​Data Definition Language Commands

Write SQL Create table statements to create the following Employee Database schema.
Include all appropriate primary and foreign key declarations. Choose appropriate types for
each attribute.

Performance Instructions:
SQL Constraints
SQL Constraints are rules used to limit the type of data that can go into a table,to maintain the
accuracy and integrity of the data inside table.

Constraints can be divided into following two types,


​Column level constraints​: limits only column data
​ able level constraints​: limits who let able data
T
Following are the most used constraints that can be applied to a table.

NOTNULL
UNIQUE
PRIMARYKEY
FOREIGNKEY
CHECK
DEFAULT

Using CHECK constraint at Table Level


Create table Student(s_id int NOTNULLCHECK(s_id>0),
Name varchar(60)NOTNULL,
Age (int);
CHECK constraint at Column Level
ALTER table Student add CHECK(s_id>0);

CREATEDATABASE
This command will create a database from PostgreSQL shell prompt,but user should have appropriate
privilege to create a database.

Syntax of creating the database


CREATE DATABASE dbname;
Where dbname is the name of a database to create.
If we need to choose among already created databases,that can be done using \l command Now, type
the following command to connect/select a desired database ;here, we will connect to the test
db database.
postgres=#\c test db;
This database is selected.

CREATE TABLE

CREATE TABLE table_name(


column1 datatype NOTNULL,
column2 datatype CHECK(),
column3datatype,
.....
columnNdatatype,
PRIMARYKEY(one or more columns );
);

INSERT INTO
Syntax of INSERT INTO

INSERT INTOTABLE_NAME(column1,column2,column3,...columnN)
VALUES(value1,value2,value3,...valueN);

OR
INSERT INTOTABLE_NAME VALUES(value1,value2,value3,...valueN);
Command Executed
1. employees
CREATE TYPE ​gender_enum​AS​ENUM( ​'M'​, ​'F'​);

CREATE TABLE employees (


emp_no INT PRIMARY KEY ,
birth_date DATE ,
first_name VARCHAR(14),
last_name VARCHAR(16),
gender gender_enum,
hire_date DATE
);

2. salaries
CREATE TABLE salaries (
emp_no INT PRIMARY KEY REFERENCES EMPLOYEES(emp_no),
salary INT,
from_dateDATE ,
to_date DATE
);

3. titles
CREATE TABLE titles (
emp_no INT PRIMARY KEY REFERENCES EMPLOYEES(emp_no),
title VARCHAR(50),
from_date DATE ,
to_date DATE
);

4. departments
CREATE TABLE departments (
dept_no CHAR(4) PRIMARY KEY ,
dept_name VARCHAR(10)
);

5. dept_manager
CREATE TABLE dept_manager (
dept_no CHAR(4) UNIQUE REFERENCES dept_manager(dept_no),
emp_no INTUNIQUE REFERENCES employees(emp_no),
from_date DATE ,
to_date DATE
);

6. dept_emp
CREATE TABLE dept_emp (
dept_no CHAR(4) UNIQUE REFERENCES dept_manager(dept_no),
emp_no INTUNIQUE REFERENCES employees(emp_no),
from_date DATE ,
to_date DATE
);
Experiment 4
Aim:​Data Manipulation Language, & In-Built Functions

Performance Instructions:
SELECT statement with WHERE clause

SELECT column1,column2,columnN
FROM table_name
WHERE[search_condition]
We can specify a search condition using comparisonor logical operators like>,<,=,LIKE, NOT,etc. in
the where clause.

ThePostgreSQLANDandORoperatorsareusedtocombinemultipleconditionsto narrow down selected data


in a Postgre SQL statement. These two operators are called conjunctive operators.

Operators Allowed in WHERE Clause


Operator Description

= Equal

!= Not Equal

> GreaterThan

< Less Than

>= Greater Than Equal To

<= Less Than EqualTo

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a


column

ors Displays record if Both the Conditions are

OR Operator Displays record if Either a Condition is TRUE.

syntaxofANDoperatorwithWHERE clause
SELECTcolumn1,column2,columnN FROM
table_name
WHERE[condition1]AND [condition2]...AND [conditionN];
syntaxofORoperatorwithWHERE clause

SELECTcolumn1,column2,columnN FROM
table_name
WHERE[condition1]OR [condition2]...OR [conditionN]
The following is the list of Postgre SQL built-in functions:

COUNTFunction−ThePostgreSQLCOUNTaggregatefunctionisusedtocountthe
numberofrows inadatabasetable.

MAXFunction−ThePostgreSQLMAXaggregatefunctionallows usto select the


highest(maximum)valueforacertaincolumn.

MINFunction−ThePostgreSQLMINaggregatefunctionallowsustoselectthelowe
st (minimum)valueforacertaincolumn.

AVGFunction−ThePostgreSQLAVGaggregatefunctionselects theaveragevaluefor
certaintablecolumn.

SUMFunction−ThePostgreSQLSUMaggregatefunctionallowsselectingthetotalfor
anumericcolumn.

NumericFunctions−Complete list ofPostgreSQL functionsrequired to manipulate


numbersinSQL.

StringFunctions−CompletelistofPostgreSQLfunctionsrequiredtomanipulatestrings inPostgreSQL.

MinFunctionSyntax:
SelectMin(columnname)fromTablenamewherecondition;
Numericfunctions areusedprimarilyfornumericmanipulationand/ormathematical calculations.

1. POW(X,Y)/POWER(X,Y)
Thesetwofunctions returnthevalueofXraisedtothepowerofY.

testdb=# SELECTPOWER(3,3);
+---------------------------------------------------------+
|POWER(3,3)|
+---------------------------------------------------------+
|27|
+---------------------------------------------------------+
1 row inset(0.00 sec)

2. SQRT(X)
Thisfunctionreturns thenon-negativesquare rootofX.
testdb=#SELECTSQRT(49);
+---------------------------------------------------------+
|SQRT(49)|
+---------------------------------------------------------+
|7|
+---------------------------------------------------------+
1 row inset(0.00 sec)

Queries:
1. Find the names of all the employees whose salary are greater than 10000.
SELECT e.first_name FROM employees as e,salaries as s
WHERE s.salaries>10000
AND s.to_date> CURRENT_DATE AND e.emp_no=s.emp_no;

2.Find the ID and name of department manager of IT department.


select e.emp_no,e.first_name from employees as e , dept_manager as m , department as d
where e.emp_no=m.emp_no and d.dept_no=m.dept_no ,d.dept_name= ‘IT’ ;

3. Find currentdepartment manager of IT.


select e.emp_no,e.first_name from employees as e , dept_manager as m , department as d
where e.emp_no=m.emp_no and d.dept_no=m.dept_no ,d.dept_name= ‘IT’AND m.to_date>
CURRENT_DATE ;

4. Find the names of all the employees from IT department


select e.first_name from employees as e , dept_emp as m , department as d wheree.emp_no=m.emp_no
and d.dept_no=m.dept_no ,d.dept_name= ‘IT’;

5. Find the employee with title named “Assisstant”


select e.first_name from employees as e,titles as t where s.title like ‘assisstant’ and e.emp_no=t.emp_no;
Use In Built Functions to execute following queries.
1. Find the number of distinct managers.
select count(distinct emp_no) from dept_manager;

2. Find the total departments.


select count(distinct dept_no) from department;

3. Find the maximum salaryof an employee.


select max(salaries) from salaries;

4.Find sum of salaries of all IT department employee.


select sum(s.salaries) from employees as e , salaries as s , department as d where e.emp_no=s.emp_no
and d.dept_no=e.dept_no ,d.dept_name= ‘IT’;

5. Find the title of all employee who get the highest salary.
Select name,salary,dept_name from instructor where salary in (select max(salary) from instructor group by
dept_name);
Experiment 5
Aim: ​Nested Subqueries and joins.

Performance Instructions:

A subquery or Inner query or Nested query is a query within another PostgreSQL query and embedded
within the WHERE clause.

Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements along with the
operators like =, <, >, >=, <=, IN, etc.

Subqueries are most frequently used with the SELECT statement.

Subquery with SELECT statement

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

A JOIN is a means for combining fields from two tables by using values common to
each. Join Types in PostgreSQL are −
CROSS JOIN
SELECT ... FROM table1 CROSS JOIN table2 ...

INNER JOIN
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

LEFT OUTER JOIN


SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ..

RIGHT OUTER JOIN


SELECT ... FROM table1 RIGHT OUTER JOIN table2 ON conditional_expression ...

FULL OUTER JOIN


SELECT ... FROM table1 FULL OUTER JOIN table2 ON conditional_expression ...

Syntax of GROUP BY and HAVING clause:


SELECT [DISTINCT] target-list
FROM relation-list
WHERE condition
GROUP BY grouping-list
HAVING group-condition
Queries:
1. Find the id and title of all employee which have salary less than 10000.
select t.emp_no,t.title from title as t where t.title in (select e.emp_no from employees as e,salaries as
swhere s.salaries>10000and s.to_date>current_date and e.emp_no=s.emp_no);

2.Find count employee with salary greater than 100000.


select count(distinct em.emp_no) from employees as em where em.emp_no in (select e.emp_no from
employees as e,salaries as s where s.salaries>10000 and s.to_date> current_date and e.emp_no=s.emp_no);

Write SQL update queries to perform the following:


1. Set salary with a 10% hike for all employees.
update salaries set salaries = salaries+ 0.1*salaries;

2. For all current department head decrease salary 10%.


update salaries set salaries = salaries+ 0.1*salaries where emp_no in (select e.emp_no from employees as e ,
dept_manager as m where e.emp_no=m.emp_no and m.to_date> CURRENT_DATE);
Viva - Questions:
Nested queries and Join.

Q1. What are different Clauses used in SQL?

GROUP BY, HAVING, ORDER BY

Q2.What are different JOINS used in SQL?


Natural Join, EquiJoin, Inner Join, Outer Join
Q3. What are the different methods for creating the subquery.

● A subquery may occur in :


- A SELECT clause
- A FROM clause
- A WHERE clause
● The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.
● A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

Q4. Can we use joins instead of wring a subquery?

Yes

Experiment No. 6
Aim: ​Views

Performance Instructions:

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.

The PostgreSQL views are created using the CREATE VIEW statement. views can be created from a
single table, multiple tables, or another view. The PostgreSQL

CREATE VIEW syntax


CREATE [TEMP | TEMPORARY] VIEW view_name AS SELECT column1,
column2..... FROM table_name
WHERE [condition];

Sample Query
Create a view from Sailors table having sid ,sname and age of the sailors.
testdb=# CREATE VIEW sailor_view AS
SELECT sid, sname , age
FROM sailors;

Now, we can query a sailor_viewin a similar way as we query an actual


table. ​testdb=# SELECT * FROM sailors_view;

Sample Ouput

testdb# select * from sailors_view;


sid | sname | age
----+--------+-----+---
1 | Paul | 20
2 | Allen | 18
3 | Teddy | 30
4 | Mark | 55
5 | David | 40
6 | Kim | 45
7 | James | 29

Dropping VIEWS

To drop a view, use the DROP VIEW statement with the view_name.
DROP VIEW Syntax

testdb=# DROP VIEW view_name;


Queries:

1. Find current department manager of IT.


create view dm as select e.emp_no,e.first_name , d.dept_name from employees as e , dept_manager as m ,
department as d where e.emp_no=m.emp_no and d.dept_no=m.dept_no AND m.to_date>
CURRENT_DATE ;
select first_name from dm where dept_name = 'IT';

2. Find count of all department managers of IT till date.


create view itm as select e.emp_no,e.first_name , d.dept_name from employees as e , dept_manager as m ,
department as d where e.emp_no=m.emp_no and d.dept_no=m.dept_no;
select count(emp_no) from itm where dept_name = 'IT';

3. Find the employee with title named “Assisstant”


create view title as select t.emp_no,title,e.first_name from employees as e,titles as t where t.title like
'assisstant' and e.emp_no=t.emp_no;
select first_name from title;

Experiment 7
Aim: ​Procedure & Function

Performance Instructions:

Functions − These subprograms return a single value; mainly used to compute and return avalue.

Procedures − These subprograms do not return a value directly; mainly used to perform anaction.
Each PL/SQL subprogram has a name, and may also have a parameter list.

Declarative Part
It is an optional part. The declarative part for a subprogram does not start with the DECLARE keyword.
It contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms.
Executable Part
This is a mandatory part and contains statements that perform the designated action.
Exception-handling
This is an optional part. It contains the code that handles run-time errors.

Syntax forCreating a PROCEDURE


CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name[IN | OUT | IN OUT] type [,...])]
{IS | AS}
BEGIN
<procedure_body>
ENDprocedure_name;

Creating a FUNCTION
A function is created using the CREATE FUNCTION statement. The simplified syntax for the
CREATE OR REPLACE PROCEDURE statement is as follows –
CREATE [OR REPLACE] FUNCTION
function_name [(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS} BEGIN
<function_body>
END [function_name];

Consider customers table.


Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
Sample Function
Create Function to count total number of customers in customers table.
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2):=0;
BEGIN
SELECT count(*)into total
FROM customers;
RETURN total;
END;

Sample output
Function created.

Queries:

1. Find the ID and name of department manager of IT department.

create or replace function counter ()


returns numeric as $$
declare
counts numeric;
begin
select e.first_name into name from employees as e , dept_manager as m , department as d
where e.emp_no=m.emp_no and d.dept_no=m.dept_no ,d.dept_name= ‘IT’ ;
return counts;
end;
$$ language plpgsql;
select counter();

2.Write a function to find out number of current department


manager. ​create or replace function dispname()
returns numeric as $$
declare
counts numeric;
begin
select count(distinct emp_no) into counts from dept_manager;
return counts;
end;
$$ language plpgsql;
select dispname();

3. Find the employee with title named “Assisstant”

create or replace function counter ()


returns numeric as $$
declare
counts numeric;
begin
select count(*) into counts from employees ;
return counts;
end;
$$ language plpgsql;
select counter();

Viva - Questions:
Procedure
Q1. Define Stored Procedure?
Stored Procedures are created to perform one or more DML operations on Database.

Q2. Where the Procedures are stored in Database?


procedures are stored in the database ​data dictionary​.
Q4. List the different types of stored Procedures?

● User Defined Stored procedure: ​The user defined stored procedures are created by users and stored in the current
database
● System Stored Procedure: The system stored procedure have names prefixed with sp_. Its manage SQL Server through
administrative tasks. Which databases store system stored procedures are master and msdb database
● Temporary Stored procedures: The temporary stored procedures have names prefixed with the # symbol. Temporary
stored procedures stored in the tempdb databases. These procedures are automatically dropped when the connection
terminates between client and server
● Remote Stored Procedures: The remote stored procedures are procedures that are created and stored in databases on
remote servers. These remote procedures can be accessed from various servers, provided the users have the appropriate
permission
● Extended Stored Procedures: These are Dynamic-link libraries (DLL's) that are executed outside the SQL Server
environment. They are identified by the prefix xp_

Q5. Can a stored Procedure be called inside other store Procedure? How?
You ​can call one ​stored procedure from another and return a set of records by creating a temporary table into which the
called stored procedure​ (B) ​can​ insert its results or by exploring the use of CURSOR variables.
Experiment 8
Aim: ​Trigger

Performance Instructions:

A trigger is a named database object that is associated with a table, and it activates when a particular event
(e.g. an insert, update or delete) occurs for the table/views. The statement CREATE TRIGGER creates a
new trigger in PostgreSQL.

Syntax for creating a trigger

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR]| UPDATE [OR]| DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
CREATE[OR REPLACE]TRIGGER Createsorreplaces anexistingtrigger with
trigger_name the​trigger_name.​

{BEFORE|AFTER |INSTEADOF} This specifies whenthetrigger willbe


executed.

{INSERT This specifies theDML operation.


[OR]|UPDATE[OR]|DELETE}

[OFcol_name] This specifies thecolumnnamethatwillbe


updated.

[ONtable_name] This specifies thenameofthetableassociated


withthetrigger.

[REFERENCINGOLDASoNEWASn] This allowsyoutorefernewandoldvaluesfor


various DML statements,suchas INSERT,
UPDATE,andDELETE.

[FOR EACHROW] This specifies a row-leveltrigger,i.e., the trigger


willbeexecutedforeachrowbeing
affected.
WHEN(condition) This provides aconditionforrows forwhich
thetriggerwouldfire.

Sample Trigger
Sample Input that will display the salary difference between the old values and new values.

Create a trigger
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger

testdb=# CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID >0)
DECLARE
sal_diff number;
BEGIN
sal_diff:=:NEW.salary-:OLD.salary;
dbms_output.put_line('Old salary: '||:OLD.salary);
dbms_output.put_line('New salary: '||:NEW.salary);
dbms_output.put_line('Salary difference: '||sal_diff);
END;

Sample Output
Trigger created.

Syntax Dropping Trigger

The following is the DROP command, which can be used to drop an existing
trigger. ​testdb=# DROP TRIGGER trigger_name;

Queries:

1.Write a trigger which shows the old values and new values of salary after any updation.

create or replace function setamount()


returns trigger as
$BODY$
begin
if new.salaries <> old.salaries then
raise notice 'UPDATED: "%" TO "%" for "%" employee
code',old.salaries,new.salaries,old.emp_no; endif
return new;
end;
$BODY$ language plpgsql;
create trigger salary
before update
on salaries
for each row
execute procedure setamount();
update salaries
set salaries = 90000
where emp_no = 101;

2.Write a trigger which shows the old values and new values of titles after any updation.
create or replace function settitle()
returns trigger as
$BODY$
begin
if new.title != old.title then
raise notice 'UPDATED: "%" TO "%" for "%" employee code',old.title,new.title,old.emp_no;
endif
return new;
end;
$BODY$ language plpgsql;
create trigger titles
before update
on title
for each row
execute procedure settitle();
update titleset title = 'DEVELOPER'where emp_no = 101;
Viva - Questions:
Trigger

Q1.Why triggers are needed?


Triggers help the database designer ensure certain actions, such as maintaining an audit file, are
completed regardless of which program or user makes changes to the data
Q2. Write the difference between triggers and stored procedures.
Stored procedures are a pieces of the code in written in PL/SQL to do some specific task. Stored
procedures can be invoked explicitly by the user. It's like a java program , it can take some input as a
parameter then can do some processing and can return values.
On the other hand, trigger is a stored procedure that runs automatically when various events happen
(eg update, insert, delete). Triggers are more like an event handler they run at the specific event.
Trigger can not take input and they can’t return values.

Q3. Is Trigger and Constraint same? Give reasons.


A constraint is an object the database engine uses to constrain data in one table or a relationship of
tables in order to maintain database integrity. These constraints include CHECK, UNIQUE,
PRIMARY KEY, etc. Here are more details about how to ​define constraints in TSQL​.

An AFTER trigger is a special type of TSQL code block that executes when a DML statement is
executed against the table the trigger is defined on

Q4. Discuss trigger variants.

■ Data Manipulation Language (DML) Triggers


■ INSERTED and DELETED Logical Tables
■ Data Definition Language (DDL) Triggers
■ LOGON Triggers

You might also like