0% found this document useful (0 votes)
8 views65 pages

DBMS Lab Manual Student Copy FINAL

The document outlines the curriculum and objectives for the Database Management Systems Lab (6AD03) at P.R. Pote Patil College of Engineering & Management, focusing on practical skills in DBMS and RDBMS. It includes the vision and mission of the institution and department, a list of practicals, assessment strategies, and learning outcomes for students. The lab aims to equip students with essential database design and SQL operation skills, preparing them for careers in the software industry.

Uploaded by

amankokate01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views65 pages

DBMS Lab Manual Student Copy FINAL

The document outlines the curriculum and objectives for the Database Management Systems Lab (6AD03) at P.R. Pote Patil College of Engineering & Management, focusing on practical skills in DBMS and RDBMS. It includes the vision and mission of the institution and department, a list of practicals, assessment strategies, and learning outcomes for students. The lab aims to equip students with essential database design and SQL operation skills, preparing them for careers in the software industry.

Uploaded by

amankokate01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Database Management System Lab(6AD03)

P.R.POTE (PATIL) EDUCATION & WELFARE


TRUST’S GROUP OF INSTITUTIONS,

COLLEGE OF ENGINEERING& MANAGEMENT,

AMRAVATI.

Artificial Intelligence and Data Science

Year :3rd Semester: 6th

SUBJECT: Database Management Systems Lab

NAME OF LABORATORY: (6AD03)DBMS Lab


Database Management System Lab(6AD03)

Institute Vision Mission

Vision:
To flourish as a centre of excellence for producing the skilled technocrats
and committed human beings.

Mission:
▪ To create conducive environment for teaching &learning.
▪ To impart quality education through demanding academic programs.
▪ To enhance career opportunities by exposure to Industries
& recent technologies.
▪ To develop professionals with strong ethics and human values for the
betterment of society.

Department Vision Mission

Vision

• To achieve Excellence in Artificial Intelligence


and Data Science for serving thegrowing needs of Software industry and
Society

Mission

• To create an ambiance that shall foster the growth for developing innovative
and entrepreneurial skills.
• To identify areas of specialization upon which the department can
concentrate, thus promote academic growth and career opportunities.
• To develop human resource with ethical and moral values for overall
personality development to serve the society.
Database Management System Lab(6AD03)

PEO’s
• Preparation To prepare graduates to have knowledge of computer science and
competency for careers in industry.

• Core Competence To develop problem solving skills in to the graduates that


are required to analyse, design and implement solution with the computer
knowledge.

• Breadth To nurture the graduates to be an effective team member, build


proficiency in soft skills, inculcate multidisciplinary approach and the ability
to relate engineering with social context.

• Professional and lifelong learning To inculcate ethical practices,


professionalism and environmental awareness for sustainable development
among students with an attitude towards lifelong learning.
Database Management System Lab(6AD03)

Department of Artificial Intelligence and Data Science

Certificate

This is to certify that Mr./Ms…………………………………………………………..

of…..………… Semester of Bachelor of Engineering in ………………………………

Artificial Intelligence & Data Science of P. R. Pote Patil College of

Engineering & Management,Amravati, has completed the term

work satisfactory in subject

……………………. for the academic year 20……- 20….. as prescribed in the

curriculum.

Place………………… PRN No:……………………

Date…………………….. Roll No……………………

Subject Teacher Head of the Department


Database Management System Lab(6AD03)

LIST OF PRACTICALS & PROGRESSIVE ASSESSMENT FOR TERM WORK

Academic Year… 2024-2025 Course : Database Management Systems


Lab
Subject & Code: DBMS Lab ,6AD03 Semester :6th Sem

Name of Faculty : Prof. S.M.Khan

Name of Student :

PRN No……………………………………… Roll No………………………………

Sign of
Title of the Date of Date of Assessment Teacher
SN. Page
Practical / Experiment No Performance Submission Marks (15) and
Remarks
Exploration of the
1 DBMS, RDBMS and
design an
ER diagram.
To Implement Data
Definition Language
2 and Data Manipulation
Language
Create a various
3
types of integrity
constraints in SQL
Demonstrate various
4 operators, expressions
and subqueries in SQL
Analysis of the
SELECTcommand with
5
differentclauses & SET
Operators in SQL
To Implement various
6 types of joins in SQL
Implement views in
7 SQL
Construct Triggers in
8 SQL
To Established the
9 authorization in SQL

Signature of Faculty
Database Management System Lab(6AD03)

INSTRUCTIONS FOR STUDENTS

Students shall read the points given below for understanding the theoretical concepts
and practical applications.
1 Listen carefully to the lecture given by teacher about importance of subject,
curriculum philosophy, learning structure, skills to be developed, information
about equipment, instruments, procedure, method of continuous assessment,
tentative plan of work in laboratory and total amount of works to be done in a
semester.
2 Student shall undergo study visit of the laboratory for types of equipment, and
material to be used, before performing experiments.
3 Read the write up of each experiment to be performed, a day in advance.
4 Organize the work in the group and make a record of all observations.
5 Understand the purpose of experiment and its practical implications.
6 Student should not hesitate to ask any difficulty faced during conduct of practical
/exercise.
7 Write the answers of the questions allotted by the teacher during practical hours if
possible or afterwards, but immediately.
8 The student shall study all the questions given in the laboratory manual and
practice to write the answers to these questions.
9 Student should develop the habit of pear discussion / group discussion related to
experiments / exercise so that exchanges of knowledge / skills could take place.
10 Students shall attempt to develop related hands-on-skills and gain confidence.
11 Student shall focus on development of skills rather than theoretical or codified
knowledge.
12 Student shall insist for the completions of recommended Laboratory Work,
answers to the given question etc.
13 Student shall develop the habit of evolving more ideas, innovations, skills etc. that
included in the scope of the manual.
14 Student shall refer technical magazines, proceedings of the Seminars, refer website
related to the scope of the subjects and update their knowledge and skills.
15 Student should develop the habit of not depend totally on teachers but to develop
self learning techniques.
16 Student should develop the habit to interact with the teacher without hesitation
with respect to academic involved.
17 Student should develop habit to submit the practical’s exercise continuously and
progressively on the schedule dates and should get the assessment done.
18 Student should be well prepared while submitting the write up of the exercise. This
will develop the continuity of the studies and he will not be overloaded at the end
of the term.
Database Management System Lab(6AD03)

P. R. Pote (Patil) College of Engineering & Management, Amravati

Department of Artificial Intelligence and Data Science

Name of the Program: B. E. AI&DS Academic Year:2024-25


Engineering
Class:3rd Semester :6th
Batches :A1,A2,A3 Course Code:6AD03

Course/Subject: Database Systems Lab Course Owner: Prof.S.M.Khan

Sr. List of Practical’s


No
1 Exploration of the DBMS, RDBMS and design an ER diagram.
2 To Implement Data Definition Language and Data Manipulation Language
3 Create various types of integrity constraints in SQL
4 Demonstrate various operators, expressions and sub queries in SQL
5 Analysis of the SELECT command with different clauses & SET Operators in SQL
6 To Perform various types of joins in SQL
7 Implement views in SQL
8 Construct Triggers in SQL
9 Established authorization in SQL
Database Management System Lab(6AD03)

Lab Course Outcomes

After successful completion of laboratory course, the students will able to

Outcomes
SN
Students learn how to design and create a good database and use various SQL
1
operations.
2 To learn the fundamental concepts of SQL queries
3 To understand the concept of designing a database with the necessary attributes.

4 To know the methodology of Accessing, Modifying and Updating data &


information from the relational databases.
Database Management System Lab(6AD03)

Assessment Strategy:Rubrics use for Internal Examination.

Allocated
Parameters High Medium Low
Marks
Student not
Students able to Student partially
able to conduct
conduct the able to conduct
given
given the given
experiment
Performance 5 experiment with experiment with
with desired
desired output. desired output.
output.
5-4 3-1 0
Student Student answered
Student did not
answered the theQuestions
answer the
Viva Voce 5 Questions moderately
Questions.
satisfactorily. satisfactorily.
5-4 3-1 0
Total marks 10 Marks (Internal Examination)

Continues Assessment (15)+Internal Examination (10)


Grand Total Marks
=25 Marks
Database Systems Lab

PRACTICAL NO. 01

AIM OF PRACTICAL :

Exploration of the DBMS, RDBMS and Design the Entity Relationship Diagram

LEARNING OBJECTIVES: -

1. To describe the uses of DBMS within educational settings.


2. To describe benefits and structure of a relational DBMS
3. To understand the Database Designing with ER diagrams

LEARNING OUTCOMES: -

1. Design and implement a simple DBMS to integrate into a classroom lesson.


2. Study the requirements and design the ER diagrams for the databse

After studying this practical students are able to:


1. Understand the basic concepts and terminology related to DBMS.
2. Know and use the procedures to design and implement a basic DBMS
3. Design the logical schema using E R Diagrams

SOFTWARE REQUIRED:-

SN Name of Equipment/ Items /


Software Tool Specification Qty Required
1. Hardware : Computer System Computer (i3-i5 As per batch
preferable) , RAM size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

Problem Definition:

Design an E R diagram for a company having employees working in different


department on different projects

Artificial Intelligence & Data Science


Database Systems Lab

CIRCUIT DIAGRAM / BLOCK DIAGRAM:

Block Diagram of DBMS:

THEORY:

DBMS (Database Management System)


A DBMS is software that allows creation, definition and manipulation of
database, allowing users to store, process and analyze data easily. DBMS provides
us with an interface or a tool, to perform various operations like creating database,
storing data in it, updating data, creating tables in the database and a lot more.
DBMS also provides protection and security to the databases. It also
maintains data consistency in case of multiple users.
Here are some examples of popular DBMS used these days:
• MySql
• Oracle
• SQL Server
• IBM DB2
• PostgreSQL
• Amazon SimpleDB (cloud based) etc.

Characteristics of Database Management System


A database management system has following characteristics:
1. Data stored into Tables: Data is never directly stored into the database.
Data is stored into tables, created inside the database. DBMS also allows
having relationships between tables which makes the data more meaningful
and connected. You can easily understand what type of data is stored where
by looking at all the tables created in a database.
2. Reduced Redundancy: In the modern world hard drives are very cheap,
but earlier when hard drives were too expensive, unnecessary repetition of

Artificial Intelligence & Data Science


Database Systems Lab

data in database was a big problem. But DBMS follows Normalization which
divides the data in such a way that repetition is minimal.
3. Data Consistency: On Live data, i.e. data that is being continuously
updated and added, maintaining the consistency of data can become a
challenge. But DBMS handles it all by itself.
4. Support Multiple user and Concurrent Access: DBMS allows multiple
users to work on it (update, insert, and delete data) at the same time and still
manages to maintain the data consistency.
5. Query Language: DBMS provides users with a simple Query language,
using which data can be easily fetched, inserted, deleted and updated in a
database.
6. Security: The DBMS also takes care of the security of data, protecting the
data from un-authorized access. In a typical DBMS, we can create user
accounts with different access permissions, using which we can easily
secure our data by restricting user access.
7. DBMS supports transactions, which allows us to better handle and manage
data integrity in real world applications where multi-threading is extensively
used.

Advantages of DBMS
➢ Segregation of application program.
➢ Minimal data duplicity or data redundancy.
➢ Easy retrieval of data using the Query Language.
➢ Reduced development time and maintenance need.
➢ With Cloud Datacenters, we now have Database Management Systems
capable of storing almost infinite data.
➢ Seamless integration into the application programming languages which
makes it very easier to add a database to almost any application or website.
Disadvantages of DBMS
➢ It's Complexity
➢ Except MySQL, which is open source, licensed DBMSs are generally costly.
➢ They are large in size.

RDBMS (Relational Database management System)


A Relational Database management System (RDBMS) is a database
management system based on the relational model introduced by E.F Codd. In

PRPCEM, Amravati 3
Database Systems Lab

relational model, data is stored in relations (tables) and is represented in form


of tuples (rows).
RDBMS is used to manage Relational database. Relational database is a collection of
organized set of tables related to each other, and from which data can be accessed
easily. Relational Database is the most commonly used database these days.
In relational model in which data is stored in multiple tables where tables are
related to each other using primary keys and foreign keys and indexes. RDBMS
uses database normalization techniques to avoid redundancy in

tables. It helps to fetch data faster using SQL query. It is widely used by enterprises
and software developers to store large amount of complex data.
Examples:
• SQL server,
• Oracle
• MySQL
• MariaDB
• SQLite

Important Concept Related to RDBMS:

Table
In Relational database model, a table is a collection of data elements organized in
terms of rows and columns. A table is also considered as a convenient
representation of relations. But a table can have duplicate row of data while a
true relation cannot have duplicate data. Table is the simplest form of data storage.
Below is an example of an Employee table.

ID Name Age Salary

1 Asha 34 13000

2 Anand 28 15000

3 Surabhi 20 18000

4 Rani 42 19020

Tuple
A single entry in a table is called a Tuple or Record or Row. A tuple in a table

PRPCEM, Amravati 4
Database Systems Lab

represents a set of related data. For example, the above Employee table
has 4 tuples/records/rows.

Following is an example of single record or tuple.

1 Asha 34 13000

Attribute
A table consists of several records (row), each record can be broken down into
several smaller parts of data known as Attributes. The above Employee table
consists offourattributes, ID, Name, Age and Salary.

Attribute Domain
When an attribute is defined in a relation (table), it is defined to hold only a certain
type of values, which is known as Attribute Domain. Hence, the
attribute Name will hold the name of employee for every tuple. If we save
employee's address there, it will be violation of the Relational database model.

Name

Asha

Anand

Surbhi - 9/401, OC Street, Amsterdam

Advantages of RDBMS
➢ It is easy to use.
➢ It is secured in nature.
➢ The data manipulation can be done.
➢ It limits redundancy and replication of the data.
➢ It offers better data integrity.
➢ It provides better physical data independence.

➢ It offers logical database independence i.e. data can be viewed in different


ways by the different users.
➢ It provides better backup and recovery procedures.
➢ It provides multiple interfaces.

PRPCEM, Amravati 5
Database Systems Lab

➢ Multiple users can access the database which is not possible in DBMS.
Disadvantages of RDBMS
➢ Software is expensive.
➢ Complex software refers to expensive hardware and hence increases
overall cost to avail the RDBMS service.
➢ It requires skilled human resources to implement.
➢ Certain applications are slow in processing.
➢ It is difficult to recover the lost data.
E.R Model:
The entity-relationship (E-R) data model is based on a perception of a real world
that consists of a set of basic objects called entities, and of relationships among
these objects.

The model is intended primarily for the database-design process. It was de-
veloped to facilitate database design by allowing the specification of an enterprise
schema. Such a schema represents the overall logical structure of the database.
This overall structure can be expressed graphically by an E-R diagram.

Entity: An entity is an object that exists in the real world and is distinguishable
from other objects. We express the distinction by associating with each entity a set
of attributes that describes the object. Ex: Student having attributes id, name, age,
etc. Entity is represented by a Rectangle as follows:
.

Weak Entity: An entity set that does not have sufficient attributes to form a primary
key is termed a weak entity set. An entity set that has a primary key is termed a
strong entity set
A strong entity is represented by simple rectangle as shown above. A weak
entity is represented by two rectangles as shown below.

PRPCEM, Amravati 6
Database Systems Lab

A relationship is an association among several entities. The collection of all entities


of the same type is an entity set, and the collection of all relationships of the same
type is a relationship set.

A superkey of an entity set is a set of one or more attributes that, taken collec-
tively, allows us to identify uniquely an entity in the entity set. We choose a minimal
superkey for each entity set from among its superkeys; the minimal superkey is
termed the entity set’s primary key. Similarly, a relationship set is a set of one or
more attributes that, taken collectively, allows us to identify uniquely a relationship
in the relationship set. Likewise, we choose a mini-

Attribute: An oval shape is used to represent the attributes. Name of the attribute is
written inside the oval shape and is connected to its entity by a line. Each Attribute
belongs to a domain which is set of permissible values of the attribute. The
attributes can be of may types:
Simple attribute: If an attribute cannot be divided into simpler components, it is a
Simple attribute. Example for simple attribute : employee_id of an employee.

Composite attribute: If an attribute can be split into components, it is called a


composite attribute. Example for composite attribute : Name of the employee
which can be split into First_ name, Middle_name, and Last_name.

Single valued Attributes: If an attribute can take only a single value for each
entity instance, it is a single valued attribute. example for single valued attribute :
age of a student. It can take only one value for a particular student.

Multi-valued Attributes
Multivalued attributes are represented by double oval shape; whereas
derived attributes are represented by oval shape with dashed lines. A composite
attribute is also represented by oval shape, but these attribute will be connected to
its parent attribute forming a tree structure.
PRPCEM, Amravati 7
Database Systems Lab

Primary Key: An underline to the attribute name is put to represent the primary
key. The key attribute of the weak entity is represented by dashed underline.

Relationship: A diamond shape is used to show the relationship between the


entities. A mapping with weak entity is shown using double diamond. Relationship
name will be written inside them.

Cardinality of Relationship: Different developers use different notation to


represent the cardinality of the relationship. Not only for cardinality, but for other
objects in ER diagram will have slightly different notations. But main difference is
noticed in the cardinality. For not to get confused with many, let us see two types of
notations for each.
One-to-one relation: - A one-to-one relationship is represented by adding ‘1’ near
the entities on the line joining the relation. In another type of notation one dash is
added to the relationship line at both ends.

One-to-Many relation: A one-to-many relationship is represented by adding ‘1’


near the entity at left hand side of relation and ‘N’ is written near the entity at right
PRPCEM, Amravati 8
Database Systems Lab

side. Other type of notation will have dash at LHS of relation and three arrow kind of
lines at the RHS of relation as shown below.

Many-to-Many relation: A one-to-many relationship is represented by adding ‘M’


near the entity at left hand side of relation and ‘N’ is written near the entity at right
side. Other type of notation will have three arrow kinds of lines at both sides of
relation as shown below.

Participation Constraints: Total participation constraints are shown by double


lines and partial participations are shown as single line.

PRPCEM, Amravati 9
Database Systems Lab

PROCEDURE/FLOW-CHARTS

PRPCEM, Amravati 10
Database Systems Lab

E R Diagram for Company Database:

OUTPUT / RESULTS & ANALYSIS:

Sr.No. DBMS RDBMS

DBMS applications store data as RDBMS applications store data


1)
file. in a tabular form.

2) In DBMS, data is generally stored in In RDBMS, the tables have an


either a hierarchical form or a identifier called primary key
navigational form. and the data values are stored in
the form of table

Normalization is not present in Normalization is present in


3)
DBMS. RDBMS.

PRPCEM, Amravati 11
Database Systems Lab

4) DBMS does not apply any RDBMS defines the integrity


security with regards to data constraint for the purpose of
manipulation. ACID (Atomicity, Consistency,
Isolation and Durability)
property.

5) DBMS uses file system to store data, in RDBMS, data values are
so there will be no relation stored in the form of tables, so
between the tables. a relationship between these
data values will be stored in the
form of a table as well.

DBMS has to provide some uniform RDBMS system supports a


6)
methods to access the stored tabular structure of the data and
information. a relationship between them to
access the stored information.

7) DBMS does not support distributed RDBMS supports distributed


database. database.

8) DBMS is meant to be for small RDBMS is designed to handle


organization and deal with small large amount of data. it
data. it supports single user. supports multiple users.

Examples of DBMS are file Example of RDBMS


9)
systems, xml etc. are mysql, postgre, sql
server, oracle etc.

CONCLUSION:-
Thus, we have studied the DBMS RDMS with its advantages and disadvantages and
various E-R model symbols also created a E-R model using these symbols, the relationship
between entity like on-to-one, on-to-many, many-to-many, primary key, attribute etc

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 12
Database Systems Lab

PRACTICAL NO. 02

AIM OF PRACTICAL :

To Implement Data Definition Language and Data Manipulation Language

LEARNING OBJECTIVES: -

1. To study SQL basics and Different SQL DDL commands like CREATE,
ALTER, RENAME and DROP.
2. To study different SQL DML commands like SELECT, INSERT, UPDATE,
DELETE

LEARNING OUTCOMES: -

a. Use different ways of imposing the integrity constraints on the relations.


b. Design and implement a simple relation to get the results.

After studying thispractical students are able to:


1. Understand the basic concepts commands for the creation of a relation.
2. Learn the use of basic commands for data manipulation.

PROBLEM DEFINITION:
Create table to store information of students and their departmentsas follows:

Student (id, name, age, phone, address, deptid)


Department (deptid, dname, location)

a) Create a table with several attributes and different constarints.


b) Describe the schema of the table
c) Add a column BTno in students table.
d) Change the data type of BTno.
e) Rename the column phone to phno.
f) Delete the column age.
g) Rename the table department as Branch
h) Delete the table data.
i) Delete the table schema.

PRPCEM, Amravati 13
Database Systems Lab

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Specification
Software Tool Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

CIRCUIT DIAGRAM / BLOCK DIAGRAM:

Block Diagram of SQL Commands:

THEORY:-
SQL is Structured Query Language, which is a computer language for
storing, manipulating and retrieving data stored in relational database. SQL is the
standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, Postgres
and SQL Server use SQL as standard database language. The database used in the
practical is MySQL or Oracle .
The SQL provides the set of commands to perform different operations on the
database.

These commands are classified into different types:


1. Data Definition Language

PRPCEM, Amravati 14
Database Systems Lab

2. Data Manipulation language


3. Data Control Language
4. Transaction Control Language

TCL (Transaction Control Language) :

Transaction Control Language commands are used to manage transactions in the


database. These are used to manage the changes made by DML-statements. It also
allows statements to be grouped together into logical transactions.

Examples of TCL commands –

COMMIT: Commit command is used to permanently save any transaction


into the database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction sothat
you can rollback to that point whenever necessary.
DCL (Data Control Language) :

A Data Control Language is a syntax similar to a computer programming language


used to control access to data stored in a database (Authorization). In particular, it is
a component of Structured Query Language (SQL).

Examples of DCL commands :


GRANT: allow specified users to perform specified tasks.
REVOKE: cancel previously granted or denied permissions.

Data Definition Language


The data definition language is used to create an object, alter the structure of an
object and also drop already created object. The Data Definition Languages used
for table definition can be classified into following:
• Create table command
• Alter table command
• Truncate table command
• Drop table command

PRPCEM, Amravati 15
Database Systems Lab

Data manipulation Language:


DML commands are the most frequently used SQL commands and is used to
query and manipulate the existing database objects. Some of the commands are
Insert, Select, Update, Delete.

DDL Commands :
1) CREATE TABLE : It is used to create a table
Syntax:
CREATE TABLE table_name (column_name1 data_ type constraints,
column_name2 data_ type Constraints …);
CREATE TABLE TABLE_NAME (COLUMN_NAME
DATATYPES[,. .. ]);

Rules:
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. 2 different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is ‘null’.

2) ALTER TABLE: Alter command is used to:


1. Add a new column.
2. Modify the existing column definition.
3. Drop a column
4. Rename a column name
5. Add or drop integrity constraints.
Syntax:
ALTER TABLE <table_name> [add/drop/modify] attributes datatype (size)
constraints;
ALTER TABLE <table_name> renames oldclname to newcolname;
ALTER TABLE <table_name> modify <colname> [add / drop] <constraint
name>constraint;

ALTER TABLE MODIFY(COLUMN DEFINITION ..... );

PRPCEM, Amravati 16
Database Systems Lab

3) DESCRIBING TABLE: used to describe the table schema


Syntax: Desc <table_name>;

4) RENAME: this command is used to change the name of table view sequence or
synonym.
Syntax: rename <old name> to <new name>;

5) DROP TABLE: It will delete the table structure provided the table should be
empty.
Syntax: drop table <table_name>;

6) TRUNCATE TABLE: If there is no further use of records stored in a table and the
structure has to be retained then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;

DML COMMANDS:
DML commands are the most frequently used SQL commands and is used to query
and manipulate the existing database objects. Some of the commands are INSERT,
SELECT, UPDATE, DELETE.

1. INSERT Command: This is used to add one or more rows to a table. The values
are separated by commas and the data types char and date are enclosed in
apostrophes. The values must be entered in the same order as they are defined.
• Inserting a single row into a table:
Syntax: insert into <table name> values (value list)
• Inserting more than one record using a single insert commands:
Syntax: insert into <table name> values (&col1, &col2…)
• Skipping the fields while inserting:
Insert into <table_name (column names to which data to b inserted)>
values (list of values);
Other way is to give null while passing the values.

INSERT INTO TABLE_NAME (col1, col2, col3,. ... col N)


VALUES (value1, value2, value3, valueN);
Or
INSERT INTO TABLE_NAME
VALUES(value1, value2, value3, .valueN);

PRPCEM, Amravati 17
Database Systems Lab

2. SELECT Commands: It is used to retrieve information from the table. it is


generally referred to as Querying the table. We can either display all columns
in a table or only specify column from the table.
• Selects all rows from the table
Syntax: Select * from <table_name>;

• The retrieval of specific columns from a table: It retrieves the specified


columns from the table
Syntax: Select column_name1, ….., column_namen from <table
name>;
• Select command with where clause: To select specific rows from a table we
include where’ clause in the select command. It can appear only after the
‘from’ clause.
Syntax: Select column_name1, ….., column_name from
<table_name> where <condition>;

3. UPDATE - It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
Syntax:
UPDATE <table name> set (fieldname-1 = value, fieldname-2 = value,…,
fieldname-n = value) [WHERE <condition/expression>];

4. DELETE - After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.
Syntax:
DELETE FROM<table name> [where <condition/expression>];

PROCEDURE/FLOW-CHARTS

PRPCEM, Amravati 18
Database Systems Lab

OUTPUT / RESULTS & ANALYSIS:

a) Create a table with several attributes and different constarints.

Create table student (sid int primary Key, sname varchar(15) not null, age int,
phone int(10), deptid int );

Create Table department( deptid int primary key, dname varchar(20) , location
varchar(10));

b) Describe the schema of the table


Desc Student;

c) Add a column BTno in students table.


Alter Table student add BTno int(5) not null;

d) Change the data type of BTno.


Alter Table student modify BTno varchar(10) not null,

e) Rename the column phone to phno.


Alter Table student change phone phno int(10);

f) Delete the column age.


Alter Table student drop age;

g) Rename the table department as Branch


Rename table department to branch;
h) Delete the table data.
Truncate department;

i) Delete the table schema.


Drop table department;

PRPCEM, Amravati 19
Database Systems Lab

CONCLUSION:-
Thus we have studied the syntax and the use of different DDL &DML statements
used in SQL. The DDL &DML statements can be used in different ways to perform
creation & manipulation of the data on one or many tables.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 20
Database Systems Lab

PRPCEM, Amravati 21
Database Systems Lab

PRACTICAL NO. 03

AIM OF PRACTICAL :

To Create various types of integrity constraints in SQL

LEARNING OBJECTIVES: -

1. To understand the use of key in formulating the relation.

2. To know the importance of having a redundancy free relation

LEARNING OUTCOMES: -

1. Implement the rules of data normalization to improve DBMS design


2. Design and implement a constraint in DBMS

After studying this practical students are able to:


1. Understand the basic constraint and terminology related to DBMS.
2. Know and use the key to design and implement a DBMS

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Specification
Software Tool Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:
Add the actual data of the students and department in the tables created in practical
2 and perform the following Queries.
a) Make Id of Student a primary key.
b) Make the Name and address field as not null.
c) Impose constraint on BTno such that values are unique.
d) Insert default value of age as 20
e) Insert multiple rows in the table one by one

PRPCEM, Amravati 22
Database Systems Lab

f) Insert multiple rows using single query.


g) Insert some rows skipping values of some attributes.
h) Display the complete data entered into the tables.
i) Update student name whose id is 3
j) Change address and phone no of student with name XYZ.
k) Delete the phone no of student 23.
l) Delete the students who belong to Amravati city.
m) Display all students who belong to city Akola.
n) Display the student names with their department names.

CIRCUIT DIAGRAM / BLOCK DIAGRAM:

Block Diagram of Constraint:

THEORY:

Database Constarints:
Integrity Constraint: An integrity constraint is a mechanism used by oracle to
prevent invalid data entry into the table. It has enforcing the rules for the columns in
a table. The types of the integrity constraints are:
a) Domain Integrity b) Entity Integrity c) Referential Integrity

a) Domain Integrity: it is also called as Attribute constraints. This constraint


sets a range and any violations that take place will prevent the user from
performing the manipulation that caused the breach. The scope of it is only one
attribute. It includes:

PRPCEM, Amravati 23
Database Systems Lab

I. Not Null constraint:


While creating tables, by default the rows can have null value .the
enforcement of not null constraint in a table ensure that the table contains
values.
Principle of null values:
• Setting null value is appropriate when the actual value is unknown, or
when a value would not be meaningful.
• A null value is not equivalent to a value of zero.
• A null value will always evaluate to null in any expression.
• When a column name is defined as not null, that column becomes a
mandatory i.e., the user has to enter data into it.
• Not null Integrity constraint cannot be defined using the alter table
command when the table contain rows.
• Syntax: create table <tbnm> (attr1 datatype not null,……)

II. Check Constraint: Check constraint can be defined to allow only a


particular range of values when the manipulation violates this constraint,
the record will be rejected. Check condition cannot contain sub queries.
• Syntax: create table <tbnm> (attr1 datatype check (condition),……)

III. Default Constraint: It is used to set the default value of the attribute to saome
dpredefine value. If the user does not provide the value, then value given as
default will be assigned.
• Syntax: create table <tbnm> (attr1 datatype Default <default
value>,……)

b) Entity Integrity: it is also called as Table constraints Maintains uniqueness


in a record. An entity represents a table and each row of a table represents
an instance of that entity. To identify each row in a table uniquely we need to
use this constraint. There are 2 entity constraints:
• Syntax: create table <tbnm> (attr1 datatype,……attr_n datatypen ,
<table constraints>);

I. Unique key constraint: It is used to ensure that information in the


column for each record is unique, as with telephone or drivers license
numbers. It prevents the duplication of value with rows of a specified column

PRPCEM, Amravati 24
Database Systems Lab

in a set of column. A column defined with the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination
of column cannot be specified. Maximum combination of columns that a
composite unique key can contain is 16.
• Syntax: create table <tbnm> (attr1 datatype,……attr_n datatypen
,Unique ( Attrlist));

II. Primary Key Constraint: A primary key avoids duplication of rows


and does not allow null values. It can be defined on one or more columns in
a table and is used to uniquely identify each row in a table. These values
should never be changed and should never be null. A table should have
only one primary key. If a primary key constraint is assigned to more than
one column or combination of column is said to be composite primary key,
which can contain 16 columns.
• Syntax: create table <tbnm> (attr1 datatype,……attr_n datatype_n
,Primary Key ( Attrlist));

c) Referential Integrity: It enforces relationship between tables. To establish


parent-child relationship between 2 tables having a common column
definition, we make use of this constraint. To implement this, we should
define the column in the parent table as primary key and same column in the
child table as foreign key referring to the corresponding parent entry.
I. Foreign key A column or combination of column included in the
definition of referential integrity, which would refer to a referenced key.
II. Referenced key: It is a unique or primary key upon which is defined
on a column belonging to the parent table.

PRPCEM, Amravati 25
Database Systems Lab

PROCEDURE/FLOW-CHARTS

Entity Integrity constraints

Referential Integrity constraints

Key constraints

PRPCEM, Amravati 26
Database Systems Lab

OUTPUT / RESULTS & ANALYSIS:

a) Make Id of Student a primary key.


Alter Table Student Modify Sid int prmary Key;

b) Make the Name and address field as not null.


Alter Table Student modify Name Varchar(25) Not Null;
Alter Table Student Modify Address varchar(25) NotNull;

c) Impose constraint on BTno such that values are unique.


Alter Table Student Modify BTno int unique;

d) Insert default value of age as 20


Alter Table Student ADD age int default(20);

e) Insert multiple rows in the table one by one


Insert into student values (23, “name”, 23, “Amravati”, 23455, 5);

f) Insert multiple rows using single query.


Insert into department values ( 2, ”CSE”, ”building1” ),
(3,”electrical”,”building2”) ;

g) Insert some rows skipping values of some attributes.


Insert into department (deptid, dname) values (3, “extc”);

h) Display the complete data entered into the tables.


Select * from Student;

i) Update student name whose id is 3


UPDATE Student set sname=”Amit” where deptid=3;

j) Change address and phone no of student with name XYZ.


UPDATE Student SET address=“Rajapeth” Phone=23456789 where
sname=”XYZ”;

PRPCEM, Amravati 27
Database Systems Lab

k) Delete the phone no of student 23.


UPDATE student SET Phone= NULL where sid=23;

l) Delete the students who belong to Amravati city.


DELETE from Student where Address=”AMRAVATI”;

m) Display all students who belong to city Akola.


SELECT * from Students where Address=”Akola”;

n) Display the student names with their department names.


SELECT sname,Dname FROM Student, Department
WHERE Student.deptid= Department.deptid;

CONCLUSION:-
Thus We have studies Different Types of Integrity Constraints that can be applied
on the Databases and also used it for different DML statements . we can Conclude
that integrity constraints helps data base to apply restrictions on the data to make
data consistent and similar to real world.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 28
Database Systems Lab

PRACTICAL NO. 04

AIM OF PRACTICAL :
Demonstrate the various operators, expressions, functions and sub queries in SQL

LEARNING OBJECTIVES: -

1. To implement different types of operator’s expressions, built in functions


and sub queries in SQL query.
2. To understand and study the use of sub queries in SQL expression.

LEARNING OUTCOMES: -

1. Learn how the particular condition should be checked


2. Study and explore the use of inbuilt functions in SQL.
After studying this practical students are able to:
1. Understand the use of operators for satisfying certain condition.
2. Learn the expressions and use of inbuilt functions & subqueries.

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Specification
Software Tool Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:
Create a table containing info of an employee working in an organization in various
dept apply some constraints, insert values and select the set of employees based on
different condition using different operator and expression. Create table for
employee and department as
Employee (empno, employee_name, address, manager, post, joining date, salary,
age) Department (Dept_id, dept_name, location )
Belongs ( Empno, Dept_id, hrs)

The department values must be (10,20,30,40,50)


PRPCEM, Amravati 29
Database Systems Lab

Perform following operations by writing queries using functions-

1) Find out the difference between maximum and minimum salary of employee.

2) Display name and date of joining of employee who join in month of January.

3) Find out the most experienced employee.

4) Display employee name in small letter.

5) Calculate experience of each employee and print with employee name.

6) Display the months between 1 June 2010 & 1 August 2012.

7) List all jobs available in employee table

8) List the employee name and salary whose salary greater than salary of any
name.

CIRCUIT DIAGRAM / BLOCK DIAGRAM:

Block Diagram of SQL operators:

THEORY:-

➢ Operators
There are mainly four types of operators are present in SQL memory.
1) Arithmetic Operators
2) Comparison Operators
3) Logical Operators
4) Operator for negating condition.

1) Arithmetic Operators
Arithmetic operators can perform arithmetical operations on numeric operands
involved. Arithmetic operators are addition (+), subtraction (-), multiplication (*)
and division (/). The + and - operators can also be used in date arithmetic.
PRPCEM, Amravati 30
Database Systems Lab

Operator Description Example

+ Addition - Adds values on either side of the operator a+b

Subtraction - Subtracts right hand operand from left hand


- a-b
operand
Multiplication - Multiplies values on either side of the
* a*b
operator

/ Division - Divides left hand operand by right hand operand b/a

Modulus - Divides left hand operand by right hand operand


% b%a
and returns remainder

2) Comparison Operators
Comparison operators are used to compare one expression to another expression.
The result at comparison is true or false or unknown depending on the condition.
Operator Description Example
Checks if the values of two operands are equal or not, if (a = b) is
=
yes then condition becomes true. not true.
Checks if the values of two operands are equal or not, if
!= (a != b)
values are not equal then condition becomes true.
Checks if the values of two operands are equal or not, if
<> (a <> b)
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the
> (a > b)
value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of
< (a < b)
right operand, if yes then 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 (a >= b)
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 (a <= b)
true.
Checks if the value of left operand is not less than the
!< (a !< b)
value of right operand, if yes then condition becomes true.
Checks if the value of left operand is not greater than the
!> (a !> b).
value of right operand, if yes then condition becomes true.

3) Logical Operators
Logical operators are used to produce a single result from the combination of two
separate conditions.

PRPCEM, Amravati 31
Database Systems Lab

Operator Description
The ALL operator is used to compare a value to all values in
ALL
another value set.
The AND operator allows the existence of multiple conditions in an
AND
SQL statement's WHERE clause.
The ANY operator is used to compare a value to any applicable
ANY
value in the list according to the condition.
The BETWEEN operator is used to search for values that are within
BETWEEN
a set of values, given the minimum value and the maximum value.
The EXISTS operator is used to search for the presence of a row in
EXISTS
a specified table that meets certain criteria.
The IN operator is used to compare a value to a list of literal values
IN
that have been specified.
The LIKE operator is used to compare a value to similar values
LIKE
using wildcard operators.
The NOT operator reverses the meaning of the logical operator
NOT with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN,
etc. This is a negate operator.
The OR operator is used to combine multiple conditions in an SQL
OR
statement's WHERE clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
The UNIQUE operator searches every row of a specified table for
UNIQUE
uniqueness (no duplicates).

4) Operators for negating condition


These operators are used to reverse the meaning of expression. We can place not
before any expression or keyword.

I) Single Row Functions:


Single row or Scalar functions return a value for every row that is processed in a
query.
There are four types of single row functions. They are:
1) Numeric Functions:
These are functions that accept numeric input and return numeric values.
Numeric functions are used to perform operations on numbers. They accept
numeric values as input and return numeric values as output. Few of the Numeric
functions are:
Function Name Return Value
ABS (x) Absolute value of the number 'x'
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'

PRPCEM, Amravati 32
Database Systems Lab

TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places


Rounded off value of the number 'x' up to the number 'y'
ROUND (x, y)
decimal places
These functions can be used on database columns.
2) Character or Text Functions: These are functions that accept character input
and can return both character and number values.
Character or text functions are used to manipulate text strings. They accept strings
or characters as input and can return both character and number values as output.
Few of the character or text functions are as given below:
Function Name Return Value
All the letters in 'string_value' is converted to
LOWER (string_value)
lowercase.
All the letters in 'string_value' is converted to
UPPER (string_value)
uppercase.
INITCAP (string_value) All the letters in 'string_value' is converted to mixed
case.
LTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the left
of 'string_value'.
RTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the
right of'string_value' .
TRIM (trim_text FROM string_value) All occurrences of 'trim_text' from the left and right
of 'string_value' ,'trim_text' can also be only one
character long .
SUBSTR (string_value, m, n) Returns 'n' number of characters
from'string_value' starting from the 'm'position.
LENGTH (string_value) Number of characters in 'string_value'in returned.
LPAD (string_value, n, pad_value) Returns 'string_value' left-padded with'pad_value' .
The length of the whole string will be
of 'n' characters.
Returns 'string_value' right-padded with 'pad_value' .
RPAD (string_value, n, pad_value) The length of the whole string will be
of 'n' characters.
3) Date Functions: These are functions that take values that are of datatype DATE
as input and return values of datatype DATE, except for the MONTHS_BETWEEN
function, which returns a number.
Few date functions are as given below.
Function Name Return Value
ADD_MONTHS (date, n) Returns a date value after adding 'n'months to the
date 'x'.
MONTHS_BETWEEN (x1, x2) Returns the number of months between dates x1
and x2.
ROUND (x, date_format) Returns the date 'x' rounded off to the nearest
century, year, month, date, hour, minute, or
second as specified by the 'date_format'.

PRPCEM, Amravati 33
Database Systems Lab

TRUNC (x, date_format) Returns the date 'x' lesser than or equal to the
nearest century, year, month, date, hour, minute,
or second as specified by the 'date_format'.
NEXT_DAY (x, week_day) Returns the next date of the 'week_day'on or after
the date 'x' occurs.
LAST_DAY (x) It is used to determine the number of days
remaining in a month from the date 'x' specified.
SYSDATE Returns the systems current date and time.
NEW_TIME (x, zone1, zone2) Returns the date and time in zone2 if date 'x'
represents the time in zone1.
4) Conversion Functions: These are functions that help us to convert a value in one
form to another form. For Example: a null value into an actual value, or a value from
one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
You can combine more than one function together in an expression. This is known
as nesting of functions.
These are functions that help us to convert a value in one form to another form. For
Ex: a null value into an actual value, or a value from one datatype to another
datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name Return Value
TO_CHAR (x [,y]) Converts Numeric and Date values to a character string
value. It cannot be used for calculations since it is a
string value.
TO_DATE (x [, Converts a valid Numeric and Character values to a Date
date_format]) value. Date is formatted to the format specified
by 'date_format'.
NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the
same datatype.
DECODE (a, b, c, d, e, Checks the value of 'a', if a = b, then returns'c'. If a = d,
default_value) then returns 'e'. Else, returns default_value.

II) Group Functions: These functions group the rows of data based on the values
returned by the query. This is discussed in SQL GROUP Functions. The group
functions are used to calculate aggregate values like total or average, which return
just one total or one average value after processing a group of rows.

5) Subqueries:
i. A Subquery or Inner query or Nested query is a query within another SQL
query and embedded within the WHERE clause.
ii. A Subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
iii. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc
iv. Nested subqueries can also be used to create a table from an existing table.

PRPCEM, Amravati 34
Database Systems Lab

Syntax:
Create table <tablename> (column1,column2-------column n) as (select
column1,column2 ------- column n from table_name);

OUTPUT / RESULTS & ANALYSIS:

1) Find out the difference between maximum and minimum salary of


employee.
select max(salary)-min(salary) as difference from emp;

2) Display name and date of joining of employee who join in month of


January.
select empname, to_char (dojoin, 'dd-mon-yyyy' ) from emp where to_char
(dojoin, 'mon' ) = 'jan';

3) Find out the most experienced employee.


SELECT empname FROM employees where DOJ in (SELECT MIN(DOJ) from
employees);

4) Display employee name in small letter.


select lower(empname),upper(pname) from emp;

5) Calculate experience of each employee and print with employee name.

select empname, (Systemdate()- doj) from employee;

6) Display the months between 1 June 2010 & 1 August 2012.


select distinct months_between('10/jan/12','01/aug/12') as difference from emp;

7) List all jobs available in employee table


Select Distinct post from employees;

8) List the employee name and salary whose salary greater than salary of any
name.
select empname, salary from emp where salary >= (select salary from emp
where empname='Ragini');

PRPCEM, Amravati 35
Database Systems Lab

CONCLUSION:-
In this practical, we study all kinds of operations performed in SQL which are
supported to program a specific task and observe the output. Using these operators
various modifications can be done in database. Also these operators are useful in
different ways for writing the query.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 36
Database Systems Lab

PRACTICAL NO. 05

AIM OF PRACTICAL :
Analysis of the SELECT command with different clauses and SET
operators in SQL.

LEARNING OBJECTIVES: -

1. To understand the use of clause such as Distinct, Order By, and


Group By, Having.
2. To implement the clauses for getting the better results.

LEARNING OUTCOMES: -

1. Learn how the particular condition should be checked


2. Design and implement a clause for group function.

After studying these practical students are able to:


1. Understand the use of where clause for satisfying certain condition.
2. Learn the use of operators ,expressions& sub queries.

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Software Tool Specification Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:

Use the tables created in practical No 4 and perform following queries in SQL:

1) List all employees who work as clerk analyst or both.

2) List all employee who work in both dept 30, 40.

PRPCEM, Amravati 37
Database Systems Lab

3) List all employees who work as analyst but not managers.

4) List number of employees who belong to same job.

5) Display total salary spent for each job.

6) List all employees in alphabetical order.

7) Display manager name and no. of employee who has more than 1 employee
working under him.

8) Display all employees in order starting from largest salary.

9) Display no. of employees working in each department along with department


name.

BLOCK DIAGRAM:

Block Diagram of SQL clauses SET Operators:

PRPCEM, Amravati 38
Database Systems Lab

THEORY:-

➢ Clauses:
We can use different clauses in SQL with select statement to retrieve the data
from the database according to the user demand these clauses can be explained
as follows:

1) DISTINCT clause:
The SQL Distinct clause is used to remove duplicates from the result set of a SELECT
statement.

Syntax:
The syntax for the SQL Distinct clause is:

SELECT DISTINCT expressions FROM tables WHERE conditions;

We can use the SQL Distinct clause to return a single field that removes the
duplicates from the result set.

2) ORDER BY Clause:

The SQL Order By clause is used to sort the records in the result set for a SELECT
statement.

Syntax:

The syntax for the SQL Order By clause is:

SELECT expressions FROM tables WHERE conditions ORDER BY expression [ ASC |


DESC];

The SQL Order By clause can be used without specifying the ASC or DESC value.
When this attribute is omitted from the SQL Order By clause, the sort order is
defaulted to ASC or ascending order.

3) GROUP BY Clause:
The SQL Group By clause can be used in a SELECT statement to collect data
across multiple records and group the results by one or more columns.

Syntax:

The syntax for the SQL Group By clause is:

SELECT expression1, expression2, ... expression_n, aggregate_function


(expression)

PRPCEM, Amravati 39
Database Systems Lab

FROM tables WHERE conditions GROUP BY expression1, expression2, ...


expression_n;

4) HAVING Clause:

The SQL Having Clause is used in combination with the GROUP BY Clause to
restrict the groups of returned rows to only those where condition is TRUE.

Syntax:

The syntax for the SQL Having Clause is:

SELECT expression1, expression2, ... expression_n, aggregate_function


(expression) FROM tables WHERE conditions GROUP BY expression1, expression2,
... expression_n HAVING condition;

SET OPERATORS:

1) Union:

The SQL Union operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows.

To use UNION, each SELECT must have the same number of columns
selected, the same number of column expressions, the same data type, and
have them in the same order, but they do not have to be the same length.

Syntax:

The basic syntax of Union is as follows:

SELECT column1 [, column2] FROM table1 [, table2] [WHERE condition]


UNION
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

2) Intersect:

Using Intersect operator, Oracle displays the common rows from both the
SELECT statements, with no duplicates and data arranged in sorted order
(ascending by default).

Syntax:

The basic syntax of Intersect is as follows:

SELECT column1 [, column2] FROM table1 [, table2] [WHERE condition]

PRPCEM, Amravati 40
Database Systems Lab

INTERSECT
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

3) Minus:

Minus operator displays the rows which are present in the first query but
absent in the second query, with no duplicates and data arranged in
ascending order by default.
Syntax:
The basic syntax of Intersect is as follows:
SELECT column1 [, column2] FROM table1 [, table2] [WHERE condition]
INTERSECT
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

OUTPUT / RESULTS & ANALYSIS:

1) List all employees who work as clerk analyst or both.

Select * from employee where post ='clerk' UNION ALL select * from
employee where post ='analyst'

2) List all employee who work in both dept 30, 40.

(select * from employee where deptid=10) INTERSECT (select * from


employee where deptid=20);

3) List all employees who work as analyst but not managers.


select * from emp where job='analyst' MINUS select * from emp
where job='manager';

4) List number of employees who belong to same job.


select post, count(Ename) from employee group by Post;

5) Display total salary spent for each job.


SELECT Post, sum(salary) from employee GROUP BY POST;

6) List all employees in alphabetical order.


SELECT ename from employee ORDER BY ename;

PRPCEM, Amravati 41
Database Systems Lab

7) Display manager name and no. of employee who has more than 1
employee working under him.

select Ename, count(Manager) from employee GROUP BY manager


HAVING count(manager) >1;

8) Display all employees in order starting from largest salary.


select * from employee ORDER BY salary DESC;

9) Display no. of employees working in each department along with


department name.

SELECT ename, deptname from employee, department where


emp.deptid = dept.deptid;

CONCLUSION:-
In this practical, we studied the use of different clauses like Having, Order by,
Group by that can be useful for using aggregate functions. Also we have studied the
use of SET opereators ;like UNION,INTERSECT and MINUS. We can conclude from
the practical that these clauses are very useful to retrieve the data from the
database as per user need.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 42
Database Systems Lab

PRACTICAL NO. 06

AIM OF PRACTICAL :

To Perform various types of joins in SQL

LEARNING OBJECTIVES: -
1. To study join operations on various tables
2. To study different types of join to retrieve the data.

LEARNING OUTCOMES: -
1. Use different ways of getting the values from various tables or relations.
2. Design and implement a simple query for retrieval of data..

After studying this practical students are able to:


1. Understand the basic commands for applying the join on a relation.
2. Learn the use of basic commands for data retrival.

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Specification
Software Tool Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:

On the table employee and department perform different join operations as follows:

1) Display id, post, deptname and dept location of employee using equijoin,
innerjoin, natural join with USING and ON clause.

2) Display id, name, location having deptid > its dept using non equijoin.

3) Display employee name manager name its department with job of manager
using self join.

4) Perform Cartesian product of employee and department table using cross join.

5) Display all the information of employee and department using left right and full
outer join.

PRPCEM, Amravati 43
Database Systems Lab

CIRCUIT DIAGRAM / BLOCK DIAGRAM:

Block Diagram of Join Operations:

THEORY:-
JOINS:
Joins play a very important role in databases as they are very much needed to
retrieve the information which is stored in different tables . the Database
Management System allows us to join the data of different tables using various types
of joins as follows:

Inner Join-
Inner join returns only those records/rows that match/exists in both the tables.
Syntax for Inner Join is as
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

PRPCEM, Amravati 44
Database Systems Lab

Outer Join-
We have three types of Outer Join.
1. Left Outer Join
Left outer join returns all records/rows from left table and from right table returns
only matched records. If there are no columns matching in the right
table, it returns NULL values. Syntax for Left outer Join is as :

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: LEFT OUTER JOIN instead of LEFT JOIN, both are same.

2. Right Outer Join


Right outer join returns all records/rows from right table and from left table returns
only matched records. If there are no columns matching in the left table, it returns
NULL values. Syntax for right outer Join is as :
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

PRPCEM, Amravati 45
Database Systems Lab

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: RIGHT OUTER JOIN instead of RIGHT JOIN, both are same.

3. Full Outer Join


Full outer join combines left outer join and right outer join. This join returns all
records/rows from both the tables.If there are no columns matching in the both
tables, it returns NULL values. Syntax for full outer Join is as :

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Cross Join
Cross join is a cartesian join means cartesian product of both the tables. This join
does not need any condition to join two tables. This join returns records/rows that
are multiplication of record number from both the tables means each row on left
table will related to each row of right table. Syntax for right outer Join is as :
Select * from table_1
cross join table_2

PRPCEM, Amravati 46
Database Systems Lab

Self Join
Self join is used to join a database table to itself, particularly when the table has a
Foreign key that references its own Primary Key. Basically we have only three types
of joins : Inner join, Outer join and Cross join. We use any of these three JOINS to
join a table to itself. Hence Self join is not a type of Sql join.

PROCEDURE/FLOW-CHARTS

OUTPUT / RESULTS & ANALYSIS:

1) Display id, post, deptname and dept location of employee using equijoin,
innerjoin, natural join with USING and ON clause.

SELECT eid, post, dname, location from Employee INNER JOIN


Department ON Employee.deptid=Department.deptid;

SELECT eid, post, dname, location from Employee INNER JOIN


Department USING (deptid);

SELECT eid, post, dname, location from Employee NATURAL JOIN


Department;

PRPCEM, Amravati 47
Database Management System Lab(6AD03)

2) Display id, name, location having deptid > its dept using non equijoin.

SELECT eid, post, dname, location from Employee INNER JOIN


Department on Employee.deptid>Department.deptid;

3) Display employee name manager name its department with job of


manager using self join.

SELECT eid, post, dname, location from Employee as E INNER JOIN


Employee as M on E.manager=M.eid;

4) Perform Cartesian product of employee and department table using cross


join.

SELECT eid, post, dname, location from Employee CROSS JOIN


Department ;

5) Display all the information of employee and department using left right
and full outer join.

SELECT eid, post, dname, location from Employee LEFT JOIN


Department on Employee.deptid=Department.deptid;

SELECT eid, post, dname, location from Employee RIGHT JOIN


Department on Employee.deptid=Department.deptid;

SELECT eid, post, dname, location from Employee FULL JOIN


Department on Employee.deptid=Department.deptid;

CONCLUSION:
Here the different joins in SQL are studied, and learned about on and using clause.
We have studied a equijoin,nonequijoin,inner join, outer join and its different types
use have studied the cross join to take a Cartesian product of two relations and we
have to come to know that using clause is not suitable for non equijoin

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 48
Database Management System Lab(6AD03)

PRACTICAL NO. 07

AIM OF PRACTICAL :
To Implement VIEWS in SQL

LEARNING OBJECTIVES: -
1. To study the concept and advantages of using Views in DBMS
2. To implement views and study the updations on views

LEARNING OUTCOMES: -
1. Learn how to simplify queries using views.
2. Design create and use views in complex queries..

After studying thispractical students are able to:


1. Identify list the advantages of using views .
2. Create and use views in SQL.

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Software Tool Specification Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:

Using the table employee and departmentt from last practical perform different
queries base on views as follows:

1) Create a view called manager which stores the information about the entire
employee who is manager.

2) 3) Create a view called manager which stores the information about the employee
and their respective department name, deptname, job and location.

4) Display information of all the view.

5) Display the manager who works in ‘10’ department.

PRPCEM, Amravati 49
Database Management System Lab(6AD03)

6) Increment salary of a manager whose age is greater than 50 by 10%.

7) Show the updated information in the view and in the logical relation.

8) Update a dept name of emp who work in CSE to IT dept and show the result of a
view as well as logical relation.

9) Drop the view.

BLOCK DIAGRAM:

Block Diagram of VIEWS:

THEORY:-

A view is nothing more than a SQL statement that is stored in the database with an
associated name. A view is actually a composition of a table in the form of a
predefined SQL query.

A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depend on the written SQL query to create a
view.

Views, which are kind of virtual tables, allow users to do the following:

1. Structure data in a way that users or classes of users find natural or intuitive.

2. Restrict access to the data such that a user can see and (sometimes) modify
exactly what they need and no more.

3. Summarize data from various tables which can be used to generate reports.

Creating Views:-
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables, or another view.

PRPCEM, Amravati 50
Database Management System Lab(6AD03)

To create a view, a user must have the appropriate system privilege according to
the specific implementation.

The basic CREATE VIEW syntax is as follows:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];

SQL Updating a View:-

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax:-

CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

SQL Dropping a View:-

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax:-

DROP VIEW view_name

OUTPUT / RESULTS & ANALYSIS:

1) Create a view called manager which stores the information about the entire
employee who is manager.

CREATE VIEW Managerview as select eid, ename , age, post,


address,deptid,salary from Employee where manager=NOT NULL;

2) Create a view called Empdata which stores the information about the
employee and their respective department name, Post and location.

CREATE VIEW EMPDATA as


select eid,ename, dname, location , post from Employee,
department where Employee.deptid=Department.deptid;

3) Display information of all the view.


Select * from Managerview;
Select * from EMPDATA;

PRPCEM, Amravati 51
Database Management System Lab(6AD03)

4) Display the manager who works in ‘10’ department.

SELECT Ename from Managerview where deptid=10;

5) Increment salary of a manager whose age is greater than 50 by 10%.

Update Managerview set salary=salary*1.1 where age>50;

6) Show the updated information in the view and in the logical relation.
Select * from Manager view ;
Select * from Employees;

7) Update a dept name of employee who work in CSE to IT dept and


show the result of a view as well as logical relation.

Update EMPDATA set dname=”IT” where Dept=”CSE”

8) Drop the view.

Drop view Managers;

CONCLUSION:-
Here in this practical we studied about creating, updating, and deleting views in
which we clear the idea about we cannot update a view which is created by join on
two or more tables along with this we can also delete a view.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 52
Database Management System Lab(6AD03)

PRACTICAL NO. 08

AIM OF PRACTICAL :
Construct Triggers in SQL

LEARNING OBJECTIVES: -
1. To study the concept and advantages of using Triggers in DBMS
2. To implement Triggers and understand how to use triggers

LEARNING OUTCOMES: -
1. Learn how to automate some actions in DBMS using triggers
2. Design create and Triggers in DBMS..

SOFTWARE REQUIRED :-

SN Name of Equipment/ Items / Qty


Software Tool Specification Required
1. Hardware : Computer System Computer (i3-i5 As per
preferable) , RAM batch size
minimum 2GB onwards
2. Operating System Windows 7 or Later
Version / LINUX version
5.0 or Later Version
3 Software MySQL / Oracle or SQL
Server

PROBLEM DEFINITION:
Create tables to store the information of product as productid, name, supplier
name, unit price.
Create another table to store the history of the product similar to product table as
productid, product name, supplier name, unit price, log date.
1) Create trigger to update to product history table when the price of product
is updated in the product table.
2) Fire the trigger by executing respective queries.

PRPCEM, Amravati 53
Database Management System Lab(6AD03)

BLOCK DIAGRAM:
Block diagram of Triggers:

THEORY:-
A trigger is a set of actions that are run automatically when a specified change
operation (SQL INSERT, UPDATE, or DELETE 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.
Uses for triggers:
• Enforce business rules
• Validate input data
• Generate a unique value for a newly-inserted row in a different file.
• Write to other files for audit trail purposes
• Query from other files for cross-referencing purposes
• Access system functions
• Replicate data to different files to achieve data consistency
Benefits of using triggers in business:
• Faster application development. Because the database stores triggers, you
do not have to code the trigger actions into each database application.
• Global enforcement of business rules. Define a trigger once and then reuse
it for any application that uses the database.

• Easier maintenance. If a business policy changes, you need to change only


the corresponding trigger program instead of each application program.

• Improve performance in client/server environment. All rules run on the


server before the result returns.

Implementation of SQL triggers is based on the SQL standard. It supports constructs


that are common to most programming languages. It supports the declaration of
local variables, statements to control the flow of the procedure, assignment of
expression results to variables, and error handling.

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. The
statement CREATE TRIGGER creates a new trigger in MySQL. Here is the syntax :
PRPCEM, Amravati 54
Database Management System Lab(6AD03)

Syntax:

CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
trigger_body
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }

trigger_name: All triggers must have unique names within a schema. Triggers in
different schemas can have the same name.
trigger_time: trigger_time is the trigger action time. It can be BEFORE or AFTER to
indicate that the trigger activates before or after each row to be modified.
trigger_event: trigger_event indicates the kind of operation that activates the
trigger. These trigger_event values are permitted:
• The trigger activates whenever a new row is inserted into the table; for
example, through INSERT, LOAD DATA, and REPLACE statements.
• The trigger activates whenever a row is modified; for example, through UPDATE
statements.
• The trigger activates whenever a row is deleted from the table; for example,
through DELETE and REPLACE statements. DROP TABLE and TRUNCATE TABLE
statements on the table do not activate this trigger, because they do not use
DELETE. Dropping a partition does not activate DELETE triggers, either.
tbl_name : The trigger becomes associated with the table named tbl_name, which
must refer to a permanent table. You cannot associate a trigger with a TEMPORARY
table or a view.
trigger_body: trigger_body is the statement to execute when the trigger activates.
To execute multiple statements, use the BEGIN ... END compound statement
construct. This also enables you to use the same statements that are permissible
within stored routines.

OUTPUT / RESULTS & ANALYSIS:


1) Create tables to store the information of product as productid, name,
supplier name, unit price.
Create table PRODUCT (pid int primary key, pname varchar(20), Supplier
varchar(20), Unit Price numeric(3,2));
2) Create another table to store the history of the product similar to product
table as productid, product name, supplier name, unit price, log date.

PRPCEM, Amravati 55
Database Management System Lab(6AD03)

Create table HISTORY (pid int primary key, pname varchar(20), Supplier
varchar(20), Unit Price numeric(3,2), logdate date);

3) Create trigger to update to product history table when the price of product
is updated in the product table.
Delimiter /
CREATE TRIGGER mytrig BEFORE UPDATE on Product
FOR EACH ROW
BEGIN
INSERT into HISTORY values( OLD.pid, OLD.pname, OLD.supplier,
OLD.UnitPrice, SYSDATE( ));
END
/
4) Fire the trigger by executing respective queries.
Update product set unitprice = 55.00 where pname=”halkefulke”;
Select * from HISTORY;

CONCLUSION:-
In this practical we have studied the triggers which are executed when insert,
update and delete operations are performed. A trigger is like a stored procedure
which invokes automatically whenever specified event occurs. Also in this practical
we come to know that triggers are a part of Pl/SQL which also supports various
conditional statements.

ASSESSMENT SCHEME:-

In Lab performance(7) Record(8) Total(15)

Signature of Faculty

PRPCEM, Amravati 56

You might also like