Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Database Management Systems Lab Manual 2022-23

Practical No: 1

Aim: To create a of database of your own name and delete (drop) using
Postgres SQL.

Objective:
PostgreSQL is a powerful, open source object-relational database system. The
main purpose is to make students familiar with its reliability and stability as it is
mostly common with the companies.

Theory:
PostgreSQL (pronounced "post-gress-Q-L") is an open source relational
database management system (DBMS) developed by a worldwide team of
volunteers. PostgreSQL is not controlled by any corporation or other private
entity and the source code is available free of charge.

Key Features:
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).
• Complex SQL queries
• SQL Sub-selects
• Foreign keys
• Trigger
• Views
• Transactions
• Multi-version concurrency control (MVCC)
• Streaming Replication (as of 9.0)
• Hot Standby (as of 9.0)

Creating a database:
This command will create a database from PostgreSQL shell prompt.
Syntax:
The basic syntax of CREATE DATABASE statement is as follows −
CREATE DATABASE dbname;
where dbname is the name of a database to create.
Example
The following is a simple example, which will create abc in your PostgreSQL
schema
postgres=# CREATE DATABASE abc;

Page | 1
Database Management Systems Lab Manual 2022-23

Output: (After Performance it is expected to take a screenshot of the


output and stick it on the left hand page)

To list all the databases available:


postgres-# \l
Output:
(After Performance it is expected to take a screenshot of the output and
stick it on the left hand page)

Connectivity:
Syntax:
postgres=# \c dbname;
Example:
Since the created dbname is abc, the query will be:
postgres=# \c abc;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

Creating Table in PostgreSQL:


After connecting to the database you have created, a table is created in the
database.
Syntax:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype);

Example:
abc-# CREATE TABLE company(id integer, Name varchar(20), Salary integer,
Department varchar(20));
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

To view the created table:


After the table is created, we need to view the table.

Syntax:
abc=# \d table_name;

Page | 2
Database Management Systems Lab Manual 2022-23

Example:
abc=# \d company;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

To view which tables are available in the system:


Syntax:
abc-# \d
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

Result: The queries are performed successfully.

Viva Questions:
1. Difference between MySql and PostgreSQL.
2. How do you login to psql shell in your system?

Page | 3
Database Management Systems Lab Manual 2022-23

Practical No: 2

Aim: To create a relation using different constraints .


Objective: To make students aware of how tables are created and modified and
what features are available to control what data is stored in the table.

Theory:
The PostgreSQL CREATE TABLE statement is used to create a new table in
any of the given database.
Syntax
Basic syntax of CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype);

Example:
abc-# CREATE TABLE company(id integer, Name varchar(20), Salary integer,
Department varchar(20));
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

The following is an example, which creates a COMPANY table with Id as


“primary key” and NOT NULL are the constraints showing that these fields
cannot be NULL while creating records in this table −
abc-# CREATE TABLE company(
Id integer primary key not null,
Name varchar(20) not null,
Salary integer);
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page)

To view the complete table:


abc-# \d tablename;

Output: (After Performance it is expected to take a screenshot of the


output and stick it on the left hand page).

Page | 4
Database Management Systems Lab Manual 2022-23

The PostgreSQL DROP TABLE statement is used to remove a table definition


and all associated data, indexes, rules, triggers, and constraints for that table.
Syntax:
Basic syntax of DROP TABLE statement is as follows −
DROP TABLE table_name;
Example:
abc-# DROP TABLE company;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

abc-# \d
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

To Drop Database:
abc-# DROP DATABASE abc;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

This statement results an error. The reason is the database is open.


Therefore it is mandatory to switch the database. Use \l command to check for
available databases in the system. Select any one database.

abc=# \c postgres;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

postgres=# \c abc;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

Alter Table:

Syntax:-

ALTER TABLE table_name ADD COLUMN new_column_name


data_type constraint;

ALTER TABLE table_name ADD COLUMN column_name1 data_type


constraint, ADD COLUMN column_name2 data_type constraint,
...

Page | 5
Database Management Systems Lab Manual 2022-23

ADD COLUMN column_namen data_type constraint;

abc-# alter table company add column dname varchar(5) not null;

Output: (After Performance it is expected to take a screenshot of the


output and stick it on the left hand page).

Result: The CREATE, DROP and ALTER commands are executed


successfully.

Page | 6
Database Management Systems Lab Manual 2022-23

Practical No: 3

Aim: To study Relational algebra operations using RelaX tool.

Objective:
It's a relational algebra calculator which calculates any relational algebra
statement like ( σ a > 42 ( A ) ) ⋈ ( π a, b ( B ) ) on a set of relations. Therefore its
necessary to make the students aware about this tool.

Theory:
Relational algebra is a procedural query language, which takes instances of
relations as input and yields instances of relations as output. It uses operators to
perform queries. An operator can be either unary or binary. They accept
relations as their input and yield relations as their output. Relational algebra is
performed recursively on a relation and intermediate results are also considered
relations.

Key Features:
The fundamental operations of relational algebra are as follows −

• Select
• Project
• Union
• Set different
• Cartesian product
• Rename

Output: (After Performance it is expected to take a screenshot of the


output along with query and stick it on the left hand page)

Result: The queries are performed successfully for relational algebra.

Page | 7
Database Management Systems Lab Manual 2022-23

Practical No: 4

Aim: To perform SQL query for creating relation Student or Emp and perform
DML operation on it. ( Select , Insert , Update, Delete).

Objective:
DML statements serve for manipulation with data in database. Therefore it is
essential that students get acquainted with these commands.

Theory:
INSERT:
The PostgreSQL INSERT INTO statement allows one to insert new rows into a
table. One can insert a single row at a time or several rows as a result of a query.
Syntax
Basic syntax of INSERT INTO statement is as follows −
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
• Here, column1, column2,...columnN are the names of the columns in the
table into which you want to insert data.
• The target column names can be listed in any order. The values supplied
by the VALUES clause or query are associated with the explicit or
implicit column list left-to-right.
Example:
CREATE TABLE company(Id integer primary key not null, Name varchar(20)
not null, Salary integer, Dept varchar(20));

Once the table is created now insert values in the table. The table will be created
in the database that you have created.

INSERT INTO company(Id, Name, Salary, Dept) VALUES(1, ‘shalu’, 20000,


‘IT’);
INSERT INTO company(Id, Name, Dept) VALUES(2, ‘swagata’, ‘civil’);
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

If you see the second query, the column salary is not written therefore it will
take default value.

SELECT:

Page | 8
Database Management Systems Lab Manual 2022-23

PostgreSQL SELECT statement is used to fetch the data from a database table,
which returns data in the form of result table. These result tables are called
result-sets.

After performing the above queries, you need to view your table and check
whether the records are entered or not.

Syntax:
SELECT * from table_name;
Example:
SELECT * from company;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

Now if you want to fetch only Id, Name fields from the table:

Syntax:
SELECT Id, Name from company;

Output: (After Performance it is expected to take a screenshot of the


output and stick it on the left hand page).

UPDATE:
The PostgreSQL UPDATE Query is used to modify the existing records in a
table.
With UPDATE query you can use WHERE clause to update the required row.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:
UPDATE company SET Name = ‘Kanchan’, Salary = 30000 WHERE Id=3;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

**Note- The update query mentioned above may differ depending on what
fields you have in your table and which record you need to update.**

DELETE:

Page | 9
Database Management Systems Lab Manual 2022-23

The PostgreSQL DELETE Query is used to delete the existing records from a
table. You can use WHERE clause with DELETE query to delete the selected
rows.
Syntax:
DELETE from table_name WHERE [condition];

Example:
DELETE from company WHERE Id = 2;
Output: (After Performance it is expected to take a screenshot of the
output and stick it on the left hand page).

Result: The SELECT, INSERT, UPDATE and DELETE queries are studied
and performed successfully.

Page | 10
Database Management Systems Lab Manual 2022-23

Practical No: 5

Aim: To Implement Select query along with SQL aggregate functions.

Theory:
Aggregate Functions:

Aggregate functions are used to compute against a "returned column of numeric data" from
your SELECT statement. They basically summarize the results of a particular column of
selected data. We are covering these here since they are required by the next topic, "GROUP
BY". Although they are required for the "GROUP BY" clause, these functions can be used
without the "GROUP BY" clause.

MIN returns the smallest value in a given column


MAX returns the largest value in a given column
returns the sum of the numeric values in a
SUM
given column
AVG returns the average value of a given column
returns the total number of values in a given
COUNT
column
COUNT(
returns the number of rows in a table
*)

For example:

SELECT AVG(salary) FROM employee;


This statement will return a single result which contains the average value of everything
returned in the salary column from the employee table.

Another example:

SELECT AVG(salary) FROM employee WHERE title = 'Programmer';


This statement will return the average salary for all employee whose title is equal to
'Programmer'

Example:

SELECT Count(*) FROM employee;

Page | 11
Database Management Systems Lab Manual 2022-23
This particular statement is slightly different from the other aggregate functions since there
isn't a column supplied to the count function. This statement will return the number of rows
in the employees table.

CONCLUSION: Aggregate function are executed successfully.

Page | 12
Database Management Systems Lab Manual 2022-23

Practical No: 6

AIM: To perform various join operations in PostgreSQL.

OBJECTIVE:
Student will able to:
⚫ Understand to perform join of columns of two or more tables.

BASIC CONCEPTS:

Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set
of data. SQL Join is used for combining column from two or more tables by using values
common to both tables. Join Keyword is used in SQL queries for joining two or more tables.
Minimum required condition for joining table, is (n-1) where n, is number of tables. A table
can also join to itself known as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.

• Inner
• Outer
• Left
• Right

Cross JOIN or Cartesian Product


This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a
table which consists of records which combines each row from the first table with each row
of the second table.
Cross JOIN Syntax is,
SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;

Example of Cross JOIN


The class table,

Page | 13
Database Management Systems Lab Manual 2022-23

ID NAME

1 abhi

2 adam

4 alex

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,


SELECT *
from class,
cross JOIN class_info;
The result table will look like,
ID NAME ID Address

1 abhi 1 DELHI

2 adam 1 DELHI

4 alex 1 DELHI

1 abhi 2 MUMBAI

2 adam 2 MUMBAI

4 alex 2 MUMBAI

1 abhi 3 CHENNAI

2 adam 3 CHENNAI

Page | 14
Database Management Systems Lab Manual 2022-23

4 alex 3 CHENNAI

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the query.
Inner Join Syntax is,
SELECT column-name-list
from table-name1
INNER JOIN
table-name2
WHERE table-name1.column-name = table-name2.column-name;

Example of Inner JOIN


The class table,
ID NAME

1 abhi

2 adam

3 alex

4 anu

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,


SELECT * from class, class_info where class.id = class_info.id;
The result table will look like,

Page | 15
Database Management Systems Lab Manual 2022-23

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
Natural Join Syntax is,
SELECT *
from table-name1
NATURAL JOIN
table-name2;
Example of Natural JOIN
The class table,
ID NAME

1 abhi

2 adam

3 alex

4 anu

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Natural join query will be,

Page | 16
Database Management Systems Lab Manual 2022-23
SELECT * from class NATURAL JOIN class_info;
The result table will look like,
ID NAME Address

1 abhi DELHI

2 adam MUMBAI

3 alex CHENNAI

In the above example, both the tables being joined have ID column(same name and same
datatype), hence the records for which value of ID matches in both the tables will be the
result of Natural Join of these two tables.
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

• Left Outer Join


• Right Outer Join
• Full Outer Join

Left Outer Join


The left outer join returns a result table with the matched data of two tables then remaining
rows of the left table and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Left outer Join Syntax for Oracle is,
select column-name-list
from table-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);

Page | 17
Database Management Systems Lab Manual 2022-23
Example of Left Outer Join
The class table,
ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,


SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);
The result table will look like,
ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

Page | 18
Database Management Systems Lab Manual 2022-23

5 ashish null null

Right Outer Join


The right outer join returns a result table with the matched data of two tables then remaining
rows of the right table and null for the left table's columns.
Right Outer Join Syntax is,
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,
select column-name-list
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;

Example of Right Outer Join


The class table,
ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,

Page | 19
Database Management Systems Lab Manual 2022-23

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Right Outer Join query will be,


SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id);
The result table will look like,
ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

null null 7 NOIDA

null null 8 PANIPAT

Full Outer Join


The full outer join returns a result table with the matched data of two table then remaining
rows of both left table and then the right table.
Full Outer Join Syntax is,
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Example of Full outer join is,
The class table,

Page | 20
Database Management Systems Lab Manual 2022-23

ID NAME

1 abhi

2 adam

3 alex

4 anu

5 ashish

The class_info table,


ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Full Outer Join query will be like,


SELECT * FROM class FULL OUTER JOIN class_info on (class.id=class_info.id);
The result table will look like,
ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

Page | 21
Database Management Systems Lab Manual 2022-23

null null 7 NOIDA

null null 8 PANIPAT

CONCLUSION: Join operations are executed successfully.

Page | 22
Database Management Systems Lab Manual 2022-23

Practical No: 7
AIM: To perform trigger operations in PostgreSQL.

OBJECTIVE:
Student will able to:
⚫ Understand how to perform trigger based operations.

BASIC CONCEPTS:
PostgreSQL Triggers are database callback functions, which are automatically
performed/invoked when a specified database event occurs.
The following are important points about PostgreSQL triggers −
• PostgreSQL trigger can be specified to fire
o Before the operation is attempted on a row (before constraints
are checked and the INSERT, UPDATE or DELETE is
attempted)
o After the operation has completed (after constraints are checked
and the INSERT, UPDATE, or DELETE has completed)
o Instead of the operation (in the case of inserts, updates or deletes
on a view)

Syntax

CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_name


ON table_name
[
-- Trigger logic goes here....
];

Example :

CREATE TABLE COMPANY(


ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
CREATE TABLE AUDIT(
EMP_ID INT NOT NULL,
ENTRY_DATE TEXT NOT NULL
);

Page | 23
Database Management Systems Lab Manual 2022-23
CREATE TRIGGER example_trigger AFTER INSERT ON COMPANY
FOR EACH ROW EXECUTE PROCEDURE auditlogfunc()

CREATE OR REPLACE FUNCTION auditlogfunc() RETURNS TRIGGER AS $example_table$


BEGIN
INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, current_timestamp);
RETURN NEW;
END;
$example_table$ LANGUAGE plpgsql;

INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Paul', 32, 'California', 20000.00 )

SELECT * FROM pg_trigger; (Listing)

DROP TRIGGER trigger_name;

CONCLUSION: Trigger operations are executed successfully.

Page | 24
Database Management Systems Lab Manual 2022-23

Practical No: 8
AIM : To perform transaction control (TCL) using PostgreSQL commands.

OBJECTIVE:
Student will able to:
⚫ Understand to manage the transaction in databases when changes made by DML
statements.

PRE-REQUISITS: Basics of DML and DDL commands.

BASIC CONCEPTS:

TCL command
Transaction Control Language (TCL) commands are used to manage transactions in
database.These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.
Commit command
Commit command is used to permanently save any transaction into database.
Following is Commit command's syntax,
commit;
Rollback command
This command restores the database to last commited state. It is also use with savepoint
command to jump to a savepoint in a transaction.
Following is Rollback command's syntax,
rollback to savepoint-name;
Savepoint command
savepoint command is used to temporarily save a transaction so that you can rollback to that
point whenever necessary.
Following is savepoint command's syntax,
savepoint savepoint-name;
Example of Savepoint and Rollback

Page | 25
Database Management Systems Lab Manual 2022-23
Following is the class table,
ID NAME

1 abhi

2 adam

4 alex

Lets use some SQL queries on the above table and see the results.
INSERT into class values(5,'Rahul');
commit;
UPDATE class set name='abhijit' where id='5';
savepoint A;
INSERT into class values(6,'Chris');
savepoint B;
INSERT into class values(7,'Bravo');
savepoint C;
SELECT * from class;
The resultant table will look like,

ID NAME

1 abhi

2 adam

4 alex

5 abhijit

6 chris

7 bravo

Now rollback to savepoint B

rollback to B;

Page | 26
Database Management Systems Lab Manual 2022-23
SELECT * from class;
The resultant table will look like
ID NAME

1 abhi

2 adam

4 alex

5 abhijit

6 chris

Now rollback to savepoint A

rollback to A;
SELECT * from class;
The result table will look like
ID NAME

1 abhi

2 adam

4 alex

5 abhijit

CONCLUSION: TCL commands are executed successfully.

Page | 27
Database Management Systems Lab Manual 2022-23

Page | 28
Database Management Systems Lab Manual 2022-23
Practical No: 9

Aim: To implement simple PL/SQL program in Postgres.

Objective:
To learn procedural language designed specifically to embrace SQL statements within its
syntax. PL/SQL is a combination of SQL along with the procedural features of programming
languages.

Theory:
PostgreSQL functions, also known as Stored Procedures, allow you to carry out operations
that would normally take several queries and round trips in a single function within the
database. Functions allow database reuse as other applications can interact directly with your
stored procedures instead of a middle-tier or duplicating code.
Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.

Key Features:
The basic syntax to create a function is as follows:

CREATE [OR REPLACE] FUNCTION function_name (arguments)


RETURNS return_datatype AS $variable_name$
DECLARE
declaration;
[...]
BEGIN
< function_body >
[...]
RETURN { variable_name | value }
END; LANGUAGE plpgsql;

Where,
• function-name specifies the name of the function. [OR REPLACE] option allows
modifying an existing function. The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
The return_datatype can be a base, composite, or domain type, or can reference the
type of a table column.
• Function-body contains the executable part. The AS keyword is used for creating a
standalone function.
• plpgsql is the name of the language that the function is implemented in. Here, we use
this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined
procedural language. For backward compatibility, the name can be enclosed by single
quotes.

Example :

Page | 29
Database Management Systems Lab Manual 2022-23

Output: (After Performance it is expected to take a screenshot of the output along with
query and stick it on the left hand page)

Result: The PL/ SQL program using postgreSQL in implemented successfully .

Page | 30

You might also like