Professional Documents
Culture Documents
ETCS -457
Semester : 7C4
Batch : CSE 2018-2022
Maharaja Agrasen Institute of Technology, PSP area, Sector – 22, Rohini, New Delhi –110085
(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi
PRACTICAL RECORD
Practical Details
A) Experiments according to ITC lab syllabus prescribed by GGSIPU
Exp Experiment Name Date of Date of Remarks Marks
No. performance checking (10)
1. a. Learn to install PostgreSql. 15 /10/2021
b. Compare different Databases
such as PostgreSQL, Oracle, MySql
and Maria DB..
2. ConsiderSchema:Student 22/10/2021
(student_name, enrollment_no,
marks, area, branch) Write SQL
queries on a. DDL (eg create, alter,
drop, rename, truncate), b. DML
(eg. Insert, update, delete etc.), c.
DCL (eg. Grant, revoke etc.) d.
Built-in Functions (eg. Sum, min,
max, avg, count, lower, upper,
trim, len etc.) e. Indexes and
views: Create and Drop
3. Perform Nested Queries in 29/10/2021
PostgreSql.
4. PL/SQL 29/10/2021
a. write a program to calculate
total students enrolled areawise.
08214802718
Rishabh Sharma
EXPERIMENT-1
Aim:
a. Installing PostgreSql
b. Compare different Databases such as PostgreSQL, Oracle, MySql and Maria DB.
First, you need to go to the download page of PostgreSQL installers on the EnterpriseDB.
Step 1. Double click on the installer file, an installation wizard will appear and guide you through
multiple steps where you can choose different options that you would like to have in PostgreSQL.
08214802718
Rishabh Sharma
Step 3. Specify installation folder, choose your own or keep the default folder suggested by
PostgreSQL installer and click the Next button
Step 5. Select the database directory to store the data or accept the default folder. And click the
Next button to go to the next step:
PostgreSQL runs as a service in the background under a service account named postgres. If you
already created a service account with the name postgres, you need to provide the password of that
account in the following window.
After entering the password, you need to retype it to confirm and click the Next button:
08214802718
Rishabh Sharma
Step 7. Enter a port number on which the PostgreSQL database server will listen. The default port of
PostgreSQL is 5432. You need to make sure that no other applications are using this port.
Step 8. Choose the default locale used by the PostgreSQL database. If you leave it as default locale,
PostgreSQL will use the operating system locale. After that click the Next button.
Step 9. The setup wizard will show the summary information of PostgreSQL. You need to review it
and click the Next button if everything is correct. Otherwise, you need to click the Back button to
change the configuration accordingly.
08214802718
Rishabh Sharma
Now, you’re ready to install PostgreSQL on your computer. Click the Next button to begin installing
PostgreSQL.
Step 10. Click the Finish button to complete the PostgreSQL installation.
08214802718
Rishabh Sharma
3) Verify the Installation
There are several ways to verify the PostgreSQL installation. You can try to connect to the
PostgreSQL database server from any client application e.g., psql and pgAdmin.
The quick way to verify the installation is through the psql program.
First, click the psql application to launch it. The psql command-line program will display.
Second, enter all the necessary information such as the server, database, port, username, and
password. To accept the default, you can press Enter. Note that you should provide the password
that you entered during installing the PostgreSQL.
Third, issue the command SELECT version(); you will see the following output:
08214802718
Rishabh Sharma
PostgreSQL
MariaDB
MariaDB Tutorial provides basic and advanced concepts of MariaDB. Our MariaDB
Tutorial is designed for beginners and professionals both.
Our MariaDB Tutorial includes all topics of MariaDB such as MariaDB Tutorial with
what is mariadb, features, installation, sql, syntax, datatypes, connection, Datatabase,
create database, select database, tables, crud operation, insert, limit, update, delete,
statement, clauses, operators, aggregate function, sum, avg, MariaDB conditions,
MariaDB join etc.
What is MariaDB
MariaDB is a community based project of the MySQL relational database management system. It
is open source and relational database technology. It is a great replacement of MySQL.
08214802718
Rishabh Sharma
MariaDB is developed by original developers of MySQL after concerns raised by Oracle's acquisition
of MySQL.
MariaDB is a relational database management system. It stores data in various tables. Primary
keys and foreign keys are used to establish relationship between these tables.
• RDBMS facilitates you to implement a data source with tables, columns, and indices.
• RDBMS provides integrity of references across rows of multiple tables.
• It is used to automatically update indices.
• It is used to interpret SQL queries and operations in manipulating or sourcing data from
tables.
MySQL
MySQL is currently the most popular database management system software used for managing the
relational database. It is open-source database software, which is supported by Oracle Company. It
is fast, scalable, and easy to use database management system in comparison with Microsoft SQL
Server and Oracle Database. It is commonly used in conjunction with PHP scripts for creating
powerful and dynamic server-side or web-based enterprise applications.
It is developed, marketed, and supported by MySQL AB, a Swedish company, and written in C
programming language and C++ programming language. The official pronunciation of MySQL is not
the My Sequel; it is My Ess Que Ell. However, you can pronounce it in your way. Many small and
big companies use MySQL. MySQL supports many Operating Systems like Windows, Linux, MacOS,
etc. with C, C++, and Java languages.
MySQL is a Relational Database Management System (RDBMS) software that provides many things,
which are as follows:
Oracle SQL
The strengths of SQL provide benefits for all types of users, including application programmers,
database administrators, managers, and end users. Technically speaking, SQL is a data sublanguage.
The purpose of SQL is to provide an interface to a relational database such as Oracle Database, and
all SQL statements are instructions to the database. In this SQL differs from general-purpose
programming languages like C and BASIC. Among the features of SQL are the following:
08214802718
Rishabh Sharma
recently accepted optional part of SQL, ISO/IEC 9075-5: 1996. Flow-control statements are
commonly known as "persistent stored modules" (PSM), and the PL/SQL extension to Oracle
SQL is similar to PSM.
SQL lets you work with data at the logical level. You need to be concerned with the implementation
details only when you want to manipulate the data. For example, to retrieve a set of rows from a
table, you define a condition used to filter the rows. All rows satisfying the condition are retrieved in
a single step and can be passed as a unit to the user, to another SQL statement, or to an application.
You need not deal with the rows one by one, nor do you have to worry about how they are
physically stored or retrieved. All SQL statements use the optimizer, a part of Oracle Database that
determines the most efficient means of accessing the specified data. Oracle also provides techniques
that you can use to make the optimizer perform its job better.
• Querying data
• Inserting, updating, and deleting rows in a table
• Creating, replacing, altering, and dropping objects
• Controlling access to the database and its objects
• Guaranteeing database consistency and integrity
• SQL unifies all of the preceding tasks in one consistent language.
08214802718
Rishabh Sharma
Experiment 2
Aim:Consider Schema: Student (student_name,
enrollment_no, marks, area, branch)
Write SQL queries on
a.DDL (eg create, alter, drop, rename,truncate),
b.DML (eg. Insert, update, deleteetc.),
c.DCL (eg. Grant, revokeetc.)
d.Built- in Functions (eg. Sum, min, max, avg, count, lower, upper, trim,
lenetc.)
e.Indexes and views: Create andDrop
Theory:
• DDL(Data Definition Language) :DDL or Data Definition Language actually
consists of the SQL commands that can be used to define the database schema. It simply
deals with descriptions of the database schema and is used to create and modify the
structure of database objects in thedatabase.
Examples of DDL commands:
CREATE– is used to create the database or its objects (like table, index,
function, views, store procedure andtriggers).
DROP– is used to delete objects from thedatabase.
ALTER-is used to alter the structure of thedatabase.
TRUNCATE–is used to remove all records from a table, including all spaces
allocated for the records areremoved.
COMMENT–is used to add comments to the data dictionary.
RENAME–is used to rename an object existing in thedatabase.
.
• DML(Data Manipulation Language) :The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation
Language and this includes most of the SQLstatements.
Examples of DML:
INSERT– is used to insert data into atable.
UPDATE– is used to update existing data within atable.
DELETE– is used to delete records from a databasetable.
• DCL(Data Control Language) :DCL includes commands such as GRANT and
REVOKE which mainly deals with the rights, permissions and other controls of the
database system.Examples of DCLcommands:
GRANT-gives user’s access privileges todatabase.
REVOKE-withdraw user’s access privileges given by using the GRANTcommand.
08214802718
Rishabh Sharma
Output:
• Create
• Insert
08214802718
Rishabh Sharma
• Update
4. Delete
08214802718
Rishabh Sharma
5. Alter
6. Inbuilt Functions
08214802718
Rishabh Sharma
7. Rename
8. CreateIndex
08214802718
Rishabh Sharma
9 Drop Index
10 Drop Table
08214802718
Rishabh Sharma
11 Truncate Table
08214802718
Rishabh Sharma
EXPERIMENT - 03
AIM: Perform Nested Queries in PostgreSql.
1. SELECT
To display all the schema and data in the database.
a. student table.
b. course table.
c. student_coursetable
2. IN
The IN operator allows you to specify multiple values in a WHERE clause.
08214802718
Rishabh Sharma
The IN operator is a shorthand for multiple OR conditions.
Syntax:
SELECT
column_name(s)FROM
table_name
WHERE column_name IN (SELECT STATEMENT);
3. NOT IN
The NOT IN operator allows you to exclude multiple values in a WHERE clause.
Syntax:
SELECT
column_name(s)FROM
table_name
WHERE column_name NOT IN (SELECT STATEMENT);
4. EXISTS
The EXISTS operator is used to test for the existence of any record in a subquery.
Syntax:
SELECT column_name(s)
FROM table_nameWHERE EXISTS
(SELECTcolumn_nameFROMtable_nameWHEREcondition);
08214802718
Rishabh Sharma
5. ANY
The ANY operator returns true if any of the subquery values meet the condition.
Syntax:
SELECT
column_name(s)FROM
table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
6. ALL
The ALL operator returns true if all of the subquery values meet the condition.
Syntax:
SELECT
column_name(s)FROM
table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
08214802718
Rishabh Sharma
7. INNERJOIN
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax:
SELECT
column_name(s)FROM
table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
8. LEFTJOIN
The LEFT JOIN keyword returns all records from the left table (table1), and
the matched records from the right table ( table2 ) . The result is NULL from
the rights ide, if there is no match .
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ONtable1.column_name=table2.column_name;
9.RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table (table2), and the
08214802718
Rishabh Sharma
matched records from the left table (table1). The result is NULL from the
left side, when there is no match.
Syntax:
SELECT
column_name(s)FROM
table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ONtable1.column_name=table2.column_name;
08214802718
Rishabh Sharma
08214802718
Rishabh Sharma
Experiment 4
THEN WE SET THE RETURN TYPE OF THE FUNCTION THAT IS INTEGER AND
THEN WE SET THE LANGUAGE
08214802718
Rishabh Sharma
WE WRITE THE CODE SOTHATTHIS FUNCTION RETURNS THETOTALNO
OF STUDENTS
08214802718
Rishabh Sharma
THIS IS THE FUCTION IN SQL
08214802718
Rishabh Sharma
Write a program to calculate average marks obtained by students
residing in area that starts with"R"
08214802718
Rishabh Sharma
we write the code for the function avgmarks
08214802718
Rishabh Sharma
now in query editor to run the function we write select function name()
08214802718
Rishabh Sharma
VIVA QUESTIONS
Q1 WHAT IS A FUNCTION ?
The create function statement allows you to define a new user-defined function.
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure
and a function is, a function must always return a value, but a procedure may or may not return a value.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
08214802718
Rishabh Sharma
Experiment -5
AIM: Write the cursor to increase the marks of student by 10%.
PostgreSQL Cursor
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors:
- Implicit
cursors
- Explicit
cursors
Syntax:
declare
Using CLI:
create or replace function modify_marks(s_id integer)
returns void AS $$
declare
rec_student record;
cur_student cursor(sid integer)
for select marks
from student_marks
where student_marks.s_id = sid;
begin
-- open the cursor open
cur_student(s_id);
08214802718
Rishabh Sharma
loop
fetch cur_student into rec_student;
exit when not found;
Update student_marks
Set marks = rec_student.marks + (rec_student.marks * 10/100)
where current of cur_student;
end loop;
-- close the cursor
close cur_student;
end; $$
language plpgsql;
BEGIN
FOR rec IN (SELECT * FROM student_marks)
LOOP perform modify_marks(rec.s_id);
END LOOP;
RETURN 'UPDATED';
END;
$$ LANGUAGE PLPGSQL;
select loop_students();
OUTPUT:
08214802718
Rishabh Sharma
Before modification:
After modification:
08214802718
Rishabh Sharma
Experiment -6
AIM: Write a program to create exceptions if enrollment no. is not issued to student
by the university and raise the exception explicitly by using raise command.
PostgreSQL Exceptions
When an error occurs in a block, PostgreSQL will abort the execution of the block and
also the surrounding transaction.
To recover from the error, you can use the exception clause in the begin...end block.
Syntax:
<<label>>
declare
begin
statements;
exception
when condition [or condition...] then
handle_exception;
[when condition [or condition...] then
handle_exception;]
[when others then
handle_other_exceptions;
]
end;
Write a program to create exceptions if enrollment no. is not issued to student by the
university and raise the exception explicitly by using raise command.
Using CLI:
do
$$
declare
rec record;
s_name text = 'Ruchir';
begin
select enrollno, students.name
into strict rec
from students
where students.name = s_name;
-- catch exception
exception
when no_data_found then
raise exception 'student with Name "%" is not assigned', s_name;
end;
$$
language plpgsql;
OUTPUT:
08214802718
Rishabh Sharma
Student Found:
08214802718
Rishabh Sharma
Experiment- 7
AIM:
a. Write the procedure to get the average marks of students for branch“CSE”.
b. Write a function that accepts branch and returns the total no. of students of
the branch.
PostgreSQL Procedures
A drawback of user-defined functions is that they cannot execute transactions. In other
words, inside a user-defined function, you cannot start a transaction, and commit or
rollback it. PostgreSQL 11 introduced stored procedures that supporttransactions.
To define a new stored procedure, you use the create procedure statement.
Syntax:
create [or replace] procedure procedure_name(parameter_list)
language plpgsql
as $$
declare
-- variable
declaration begin
-- stored procedure
body end; $$
PostgreSQL Function
The create function statement allows you to define a new user-defined function.
Syntax:
create [or replace] function
function_name(param_list) returns return_type
language
plpgsql as
$$
declare
-- variable declaration
begin
-- logic
end;
$$
(A) Write the procedure to get the average marks of students for
branch“CSE”. Using CLI:
CREATE OR REPLACE PROCEDURE public.avg_marks_of_students(IN
student_branch text, INOUT avg_marks real)
LANGUAGE 'plpgsql'
AS $BODY$
begin
select avg(marks)
into avg_marks
from collegestudents
where branch = student_branch;
end;
$BODY$;
08214802718
Rishabh Sharma
OUTPUT:
(B) Write a function that accepts branch and returns the total no. of students of thebranch.
08214802718
Rishabh Sharma
For CSE:
For ECE:
08214802718
Rishabh Sharma
Experiment -8
AIM :
a. Create a trigger on table after inserting a new student intotable.
b. Write a row trigger to insert the existing values of the student table into a new
table when the marks of student areupdated.
PostgreSQL Trigger
A trigger is a set of actions that are run automatically when a specified change operation
(SQL INSERT, UPDATE, DELETE or TRUNCATE statement) is performed on a specified
table. Triggers are useful for tasks such as enforcing business rules, validating input
data, and keeping an audit trail.
Syntax:
ON table_name
[ FROM referenced_table_name ]
[ NOT DEFERRABLE | [ DEFERRABLE ] { INITIALLY IMMEDIATE | INITIALLY
DEFERRED } ]
[ FOR [ EACH ] { ROW | STATEMENT } ]
[ WHEN ( condition ) ]
EXECUTE PROCEDURE function_name ( arguments )
(A) Create a trigger on table after inserting a new student
intotable. Using CLI:
Trigger:
CREATE TRIGGER
ins_same_recAFTER
INSERT ON studentinfo
FOR EACH ROW
EXECUTE PROCEDURE rec_insert();
Trigger Function:
CREATE OR REPLACE FUNCTION
rec_insert() RETURNS trigger AS
$$
BEGIN
INSERT INTO student_added
VALUES(NEW.s_id,NEW.s_name);
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';
08214802718
Rishabh Sharma
OUTPUT:
Before Insertion:
After Insertion:
08214802718
Rishabh Sharma
(B) Write a row trigger to insert the existing values of the student table into a new
table when the marks of student areupdated.
Using CLI:
Trigger:
CREATE TRIGGERupd_same_rec
AFTERUPDATE
ONstudent_marks
FOR EACHROW
EXECUTE PROCEDURE rec_update();
Trigger Function:
CREATE OR REPLACE
FUNCTIONrec_update() RETURNS trigger
LANGUAGE 'plpgsql'
BEGIN
INSERT INTO student_modify
VALUES(Old.s_id,Old.name,Old.marks);
RETURN
NEW; END;
OUTPUT:
Before Update:
08214802718
Rishabh Sharma
After Update:
08214802718
Rishabh Sharma
08214802718
Rishabh Sharma