0% found this document useful (0 votes)
310 views

DBMS Lab Manual 2023-24

The document provides details about the syllabus for the Database Management System Lab course including teaching scheme, credit scheme, examination scheme, prerequisites, objectives, outcomes and topics to be covered in the lab sessions.

Uploaded by

Shaurya Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
310 views

DBMS Lab Manual 2023-24

The document provides details about the syllabus for the Database Management System Lab course including teaching scheme, credit scheme, examination scheme, prerequisites, objectives, outcomes and topics to be covered in the lab sessions.

Uploaded by

Shaurya Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

214456: Database Management

System Lab

Second Year – Information Technology


(2019 Course)
Academic Year 2023-24 Semester – II

Credit
Teaching Scheme: Examination Scheme:
Scheme:
Practical (PR): 04 PR: 25 TW: 25
02 Credits
hrs/week Marks Marks

LABORATORY MANUAL V 3.0


DEPARTMENT OF INFORMATION TECHNOLOGY
Sinhgad College of Engineering, Pune

2023-2024
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 1 | 77
VISION

To provide excellent Information Technology education by building


strong teaching and research environment.

MISSION
1) To transform the students into innovative, competent and high
quality IT professionals to meet the growing global challenges.

2) To achieve and impart quality education with an emphasis on


practical skills and social relevance.

3) To endeavor for continuous up-gradation of technical expertise


of students to cater to the needs of the society.

4) To achieve an effective interaction with industry for mutual


benefits.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 2 | 77
PROGRAM EDUCATIONAL OBJECTIVES
The students of the Information Technology course after passing out will:

Sr. No. Description

Possess strong fundamental concepts in mathematics, science,


PEO1
engineering, and Technology to address technological challenges.

Possess knowledge and skills in the field of Computer Science and


Information Technology for analyzing, designing, and implementing
PEO2
complex engineering problems of any domain with innovative
approaches.
Possess an attitude and aptitude for research, entrepreneurship, and
PEO3 higher studies in the field of Computer Science and Information
Technology.

Have a commitment to ethical practices, societal contributions


PEO4
through communities, and life-long learning.

Possess better communication, presentation, time management, and


PEO5 team work skills leading to responsible & competent professionals and
will be able to address challenges in the field of IT at the global level.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 3 | 77
PROGRAM OUTCOMES
The students in the Information Technology course are expected to know and be
able to:

Sr. No. PO's Description


Engineering An ability to apply knowledge of mathematics,
PO1
knowledge computing, science, engineering and technology.
An ability to define a problem and provide a
systematic solution with the help of conducting
PO2 Problem analysis
experiments, analyzing the problem and interpreting
the data.
An ability to design, implement, and evaluate
Design/Development software or a software/hardware system, component,
PO3
of Solutions or process to meet desired need switch in realistic
constraints.
Conduct An ability to identify, formulate, and provide essay
PO4 Investigation of schematic solutions to complex engineering
Complex Problems /Technology problems.
An ability to use the techniques, skills, and modern
PO5 Modern Tool Usage engineering technology tools, and standard processes
necessary for practice as an IT professional.
An ability to apply mathematical foundations,
algorithmic principles, and computer science theory
The Engineer and
PO6 in the modeling and design of computer-based
Society systems with necessary constraints and
assumptions.
An ability to analyze and provide solutions for the
Environment and
PO7 local and global impact of information technology on
Sustainability individuals, organizations, and society.
An ability to understand professional, ethical, legal,
PO8 Ethics
security and social issues and responsibilities.
Individual and Team An ability to function effectively as an individual or a
PO9
Work sate am member to accomplish a desired goal(s).
An ability to engage in life-long learning and
continuing professional development to cope up with
Communication
PO10 fast changes in the technologies /tools with the help
Skills of electives, profession along animations and extra-
curricular activities.
An ability to communicate effectively in engineering
Project Management community at large by means of effective
PO11
and Finance presentations, report writing, paper publications,
demonstrations.
An ability to understand engineering, management,
PO12 Life-long Learning financial aspects, performance, optimizations and
time complexity necessary for professional practice.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 4 | 77
PROGRAM SPECIFIC OUTCOMES
A graduate of the Information Technology Program will demonstrate-

Sr. No. Description

An ability to apply the theoretical concepts and practical knowledge of


Information Technology in analysis, design, development and
PSO1
management of information processing systems and applications in
the interdisciplinary domain.

Decision-making skills through the use of Modern IT tools to make


PSO2
ready for professional responsibilities.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 5 | 77
DOCUMENT CONTROL

Reference Code SCOE-IT / Lab Manual Procedures


Version No 3.0
Compliance Status Complete
Date of Compliance 15-12-2023
Security Classification Department Specific
Document Status Definitive
Review Period Yearly

Document History

Revision
Revision Date Reason For Change
No.
1 01-07-2021 Update
2 01-07-2022 Update
3 01-01-2024 Updating the theory content of a few assignments

Summary of Changes to Database Management Lab

Sr. No Changes Change type

1 Group A Assignment 1, 2, 3 Few theory content updated


2

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 6 | 77
SYLLABUS
Savitribai Phule Pune University, Pune
Second Year Information Technology (2019 Course)
214456: Database Management System Lab

Teaching Scheme: Credit Scheme: Examination Scheme:


Practical (PR): 04 hrs/week 02 Credits PR :25 Marks TW: 25Marks

Prerequisite Courses:
Data structures and Software engineering principles and practices.

Course Objectives:
1. Understand the fundamental concepts of database management. These
concepts include aspects of database design, database languages, and
database-system implementation.
2. To provide a strong formal foundation in database concepts, recent
technologies and best industry practices.
3. To give systematic database design approaches covering conceptual design,
logical design and an overview of physical design.
4. To learn the SQL database system.
5. To learn and understand various Database Architectures and its use for
application development.
6. To program PL/SQL including stored procedures, stored functions, cursors
and packages.

Course Outcomes:
On completion of the course, students will be able to --
CO1: Install and configure database systems.
CO2: Analyze database models & entity relationship models.
CO3: Design and implement a database schema for a given problem-domain
CO4: Implement relational database systems.
CO5: Populate and query a database using SQL DDL / DML / DCL commands.
CO6: Design a backend database of any one organization: CASE STUDY
Guidelines for Instructor’s Manual
The faculty member should prepare the laboratory manual for all the
experiments and it should be made available to students and laboratory
instructor/Assistant.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 7 | 77
Guidelines for Student's Lab Journal
1. Student should submit term work in the form of journal with write-ups
based on specified list of assignments.
2. Practical and Oral Examination will be based on all the assignments in the
lab manual.
3. Candidate is expected to know the theory involved in the experiment.
4. The practical examination should be conducted only if the journal of the
candidate is complete in all respects
Guidelines for Oral/ Practical Assessment
1. Examiners will assess the student based on performance of students
considering the parameters such as timely conduction of practical
assignment, methodology adopted for implementation of practical
assignment, timely submission of assignment in the form of handwritten
write-up along with results of implemented assignment, attendance etc.
2. Examiners will judge the understanding of the practical performed in the
examination by asking some questions related to theory & implementation of
experiments he/she has carried out.
3. Appropriate knowledge of usage of software and hardware related to
respective laboratory should be checked by the concerned faculty member.

LIST OF LABORATORY ASSIGNMENTS


Group A: Study of Databases
Mapping of Course Outcomes Group A -- CO1
1. Study of MySQL Open source software. Discuss the characteristics like
efficiency, scalability, performance and transactional properties.
2. Install and configure client and server of MySQL.(Show all commands and
necessary steps for installation and configuration).
3. Study of SQLite: What is SQLite? Uses of Sqlite. Building and installing
SQLite.
Group B: MySQL
Mapping of Course Outcomes Group B -- CO2, CO3, CO4, CO5
1. Design any database with at least 3 entities and relationships between them.
Draw suitable ER/EER diagram for the system.
2. Design and implement a database (for assignment no 1) using DDL
statements and apply normalization on them
3. Create Table with primary key and foreign key constraints.
a. Alter table with add n modify b. Drop table
4. Perform following SQL queries on the database created in assignment 1.
• Implementation of relational operators in SQL
• Boolean operators and pattern matching
• Arithmetic operations and built in functions
• Group functions
• Processing Date and Time functions
• Complex queries and set operators
5. Execute DDL/DML statements which demonstrate the use of views. Update
the base table using its corresponding view. Also consider restrictions on
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 8 | 77
updatable views and perform view creation from multiple tables.
Group C: PL/SQL
Mapping of Course Outcomes Group C -- CO6
1. Write and execute PL/SQL stored procedure and function to perform a
suitable task on the database. Demonstrate its use.
2. Write and execute suitable database triggers. Consider row level and
statement level triggers.
3. Write a PL/SQL block to implement all types of cursor.
Group D: Relational Database Design
Mapping of Course Outcomes Group D -- CO5, CO6
Design and case study of any organization (back end only), Project Proposal and
High Level SRS
To prepare for project, do the following:
1. Form teams of around 3 to 4 people
2. Create requirements document with the following information:-
a. Give one or two paragraph description of your goals for the topic(s).
b. List what all types of users will be accessing your application
c. List the various functionalities that your application will support. Explain
each in about a paragraph worth of detail.
d. List the hardware and software requirements at the backend and at the
front end.
e. Give an estimate of the number of users of each type, the expected load
(transactions per day), and the expected database size.
Project ER Diagram and Database Design
For ER diagram and Database design following guidelines can be used:
1. Draw an ER diagram of your project.
2. Reduce this ER diagram into the tables and complete database design.
3. Subsequently, list all the functional dependencies on each table that you
expect will hold.
4. Check that the database schema is in 3NF/BCNF. If it is not, apply
normalization. Use non-loss decomposition and bring the database schema in
3NF/BCNF.
Give the ER diagram and the data dictionary as part of the requirement
specifications file which you created for the project proposal.
Reference Books:
1. Dr. P. S. Deshpande, “SQL and PL/SQL for Oracle 10g Black Book”,
DreamTech
2. Ivan Bayross, “SQL, PL/SQL: The Programming Language of Oracle”, BPB
Publication
3. Reese G., Yarger R., King T., Williums H, “Managing and Using MySQL”,
Shroff Publishers and Distributors Pvt. Ltd., ISBN: 81 - 7366 - 465 – X, 2nd
Edition
4. Eric Redmond, Jim Wilson, “Seven databases in seven weeks”, SPD, ISBN:
978-93-5023-91
5. Jay Kreibich, Using SQLite, SPD, ISBN: 978-93-5110-934-1, 1st edition

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 9 | 77
GROUP A Study of MySQL Open source software. Discuss the
ASSIGNMENT NO.1 characteristics like efficiency, scalability, performance
and transactional properties.
GIVEN DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 01
AIM:
Study of MySQL Open source software. Discuss the characteristics like
efficiency, scalability, performance and transactional properties.

PREREQUISITE:
1. Data Structures
2. Software Engineering Principles

OBJECTIVES:
1. To study of different type of SQL Databases.
2. To study of advantages of various SQL Databases.
3. To compare the different database systems based on points like
efficiency, scalability, characteristics and performance.

THEORY:
What is Database?

A database is a separate application that stores a collection of data. Each


database has one or more distinct APIs for creating, accessing, managing,
searching and replicating the data it holds. So nowadays, we use
relational database management systems (RDBMS) to store and manage
huge Volume of data. This is called relational database because all the
data is stored into different tables and Relations are established using
primary keys or other keys known as foreign keys.
A software system that enables users to define, create, maintain, and
control access to the database. The DBMS is the software that interacts
with the users‟ application programs and the database.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 10 | 77
Typically, a DBMS provides the following facilities:

• It allows users to define the database, usually through a Data


Definition Language (DDL). The DDL allows users to specify the
data types and structures and the constraints on the data to be
stored in the database.
• It allows users to insert, update, delete, and retrieve data from the
database, usually through a Data Manipulation Language (DML).
The most common query language is the Structured Query
Language which is now both the formal and de facto standard
language for relational DBMS.
• It provides controlled access to the database.
For example, it may provide:
– A security system, which prevents unauthorized users
accessing the database.
– An integrity system, which maintains the consistency of
stored data;
– A concurrency control system, which allows shared access of
the database;
– A recovery control system, which restores the database to a
previous consistent state following a hardware or software
failure
– A user-accessible catalog, which contains descriptions of the
data in the database.

Advantages of DBMS:

1. Data redundancy and inconsistency


2. Difficulty in accessing data
3. Data isolation
4. Integrity Problems
5. Atomicity problem
6. Concurrent-access anomalies
7. Security Problem
8. Reduced application development time
9. Uniform data administration
10. Recovery from crashes.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 11 | 77
Disadvantages of DBMS:

1. Complexity
2. Size
3. Additional hardware costs
4. Cost of DBMS
5. Performance
6. Higher impact of failure

RDBMS Terminology:

Before we proceed to explain MySQL database system, let's revise few


definitions related to database.

Database A database is a collection of tables, with related data.


Table A table is a relation with collection of data.
Column A column is a field or attribute for that relation.
Row Tuple, or record is a group of related data.
A candidate key chosen as the principal means of
Primary key
identifying tuples within a relation.
A relation schema may have an attribute that
Foreign key corresponds to the primary key of another relation.
The attribute is called a foreign key.
The collection of information stored in the database at
Instance a particular moment is called an instance of the
database.
The overall design of the database is called the
Schema
database schema.

MySQL Database:

• MySQL is a fast, easy-to-use RDBMS being used for many small


and big businesses. MySQL is developed, marketed, and supported
by MySQL AB, which is a Swedish company.
• MySQL is released under an open-source license. It is freely
available.
• MySQL is a very powerful program in its own right. It handles large
subset of the functionality of the most expensive and powerful
database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL works very quickly and works well even with large datasets.
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 12 | 77
• MySQL supports large databases, up to 50 million rows or more in
a table. The default file size limit is 4GB, but you can increase this.
• MySQL is customizable. The open-source GPL license allows
programmers to modify the MySQL software to fit their own specific
environments.

Types of Databases:

1. SQL:

SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS). It is a
standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables. All the
RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use
SQL as their standard database language. SQL allows users to query the
database in a number of ways, using English-like statements.

SQL statements are used to perform tasks such as update data on a


database, or retrieve data from a database. Some common relational
database management systems that use SQL are: Oracle, Sybase,
Microsoft SQL Server, Access, Ingres, etc. Although most database
systems use SQL, most of them also have their own additional proprietary
extensions that are usually only used on their system. However, the
standard SQL commands such as "Select", "Insert", "Update", "Delete",
"Create", and "Drop" can be used to accomplish almost everything that
one needs to do with a database. This tutorial will provide you with the
instruction on the basics of each of these commands as well as allow you
to put them to practice using the SQL Interpreter.

2. PostgreSQL:

PostgreSQL, often simply Postgres, is an object-relational database


management system (ORDBMS) with an emphasis on extensibility and
standards compliance. As a database server, its primary functions are to
store data securely and return that data in response to requests from
other software applications. It can handle workloads ranging from small
single-machine applications to large Internet-facing applications (or for
data warehousing) with many concurrent users; on macOS Server,
PostgreSQL is the default database; and it is also available for Microsoft
Windows and Linux.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 13 | 77
PostgreSQL is ACID-compliant and transactional. PostgreSQL has
updatable views and materialized views, triggers, foreign keys; supports
functions and stored procedures, and other expandability.

PostgreSQL is developed by the PostgreSQL Global Development Group, a


diverse group of many companies and individual contributors. It is free
and open-source, released under the terms of the PostgreSQL License, a
permissive software license.

3. MySQL:

MySQL is an open-source relational database management system


(RDBMS). The MySQL development project has made its source code
available under the terms of the GNU General Public License, as well as
under a variety of proprietary agreements. MySQL was owned and
sponsored by a single for-profit firm, the Swedish company MySQL AB,
now owned by Oracle Corporation. For proprietary use, several paid
editions are available, and offer additional functionality. MySQL is a
central component of the LAMP open-source web application software
stack (and other "AMP" stacks). LAMP is an acronym for "Linux.

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What is Open source Software?


2. What are different open source databases?
3. What is difference between MySQL and SQL?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 14 | 77
GROUP A Install and configure client and server of
ASSIGNMENT NO.2 MySQL.(Show all commands and necessary steps for
installation and configuration)
GIVEN DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 02
AIM:
Install and configure client and server of MySQL. (Show all commands
and necessary steps for installation and configuration)

PREREQUISITE:
1. Knowledge of MySQL Databases.

OBJECTIVES:
1. To study of installation of client and server of MySQL.

THEORY:
What is MySQL client?

MySQL client is a common name for tools that are designed to connect to
MySQL Server. Client programs are used to send commands or queries to
the server and allow managing data in the databases stored on the server.
You can use the MySQL client to send commands to any MySQL server;
on a remote computer or your own. The MySQL clients purpose is to allow
you to use that query interface.

What is MySQL Server?

MySQL server is an open source relational database management system;


while SQL Server is not open source, it is commercial. MySQL server
represents the server and is the server side. It is the MySQL core
program, which generates and manages database instances, database
instance task scheduling threads, etc., and provides related interfaces for
different clients to call. MySQL server is short and powerful, easy to use,
simple to operate, and available for free. Compared with other databases,
it has more unique and practical syntax. MySQL server can run with

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 15 | 77
other applications, such as FTP, email and web servers. MySQL server is
configured to use an appropriate proportion of system resources.
The MySQL server package will install the MySQL database server which
you can interact with using a MySQL client. The MySQL server is used to
persist the data and provide a query interface for it (SQL).

Steps for installation of MySQL client and server:

Step 1: Installing MySQL :

1. To install it, update the package index on your server with apt

$ sudo apt update

2. Then install the default package

$ sudo apt install mysql-server

3. Ensure that the server is running using the systemctl


start command

$ sudo systemctl start mysql.service

Step 2: Configuring MySQL :

$ sudo mysql_secure_installation

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 16 | 77
QUESTIONS:
Write the answers of following questions.

1. What are the steps for installation of MySQL Client and server?
2. What is MySQL Client and MySQL Server?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 17 | 77
GROUP A Study of SQLite: What is SQLite? Uses of Sqlite.
ASSIGNMENT NO.3 Building and installing SQLite.
GIVEN DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 03
AIM:
Study of SQLite: What is SQLite? Uses of Sqlite. Building and installing
SQLite.

PREREQUISITE:
1. Knowledge of MySQL Databases.

OBJECTIVES:
1. To study of installation of SQLite.

THEORY:
What is SQLite?

SQLite is a self-contained, high-reliability, embedded, full-featured,


public-domain, SQL database engine. SQLite is the most used database
engine in the world. In contrast to many other database management
systems, SQLite is not a client– server database engine. Rather, it is
embedded into the end program.

SQLite is ACID-compliant and implements most of the SQL standard,


using a dynamically and weakly typed SQL syntax that does not
guarantee the domain integrity. SQLite is a popular choice as embedded
database software for local/client storage in application software such as
web browsers. It is arguably the most widely deployed database engine, as
it is used today by several widespread browsers, operating systems, and
embedded systems (such as mobile phones), among others.[6] SQLite has
bindings to many programming languages.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 18 | 77
Steps for installation of SQLite on Linux:

Step 1: Update the system repositories.


1. To update system repositories, open the terminal on your Ubuntu and
enter the following commands.

$ sudo apt update


$ sudo apt upgrade

2. Ensure that the server is running using the systemctl start command

$ sudo systemctl start mysql.service

Step 2: Install SQLite 3:


After upgrading the system repositories, use the following command in
Ubuntu to install SQLite3

$ sudo apt install sqlite3


Step 3: Check the SQLite installation.

Finally, confirm the installed software’s version by using the following


command.

$ sqlite3 --version

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 19 | 77
QUESTIONS:
Write the answers of following questions.

1. What is SQLite?
2. What is Difference between SQL and SQLite?
3. What are four difference features of SQLite?
4. What are features of SQLite.

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 20 | 77
GROUP B Design any database with at least 3 entities and
ASSIGNMENT NO.1 relationships between them. Draw suitable ER/EER
diagram for the system.
GIVEN DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 01
AIM:
Design any database with at least 3 entities and relationships between
them. Draw suitable ER/EER diagram for the system.

PREREQUISITE:
1. Knowledge of MySQL Databases.

OBJECTIVES:
1. To understand the ER diagram & EER diagram.

THEORY:
What is ER diagram?

ER model stands for an Entity-Relationship model. It is a high-level data


model. This model is used to define the data elements and relationship for
a specified system. It develops a conceptual design for the database. It
also develops a very simple and easy to design view of data. In ER
modeling, the database structure is portrayed as a diagram called an
entity-relationship diagram.

An Entity–relationship model (ER model) describes the structure of a


database with the help of a diagram, which is known as Entity
Relationship Diagram (ER Diagram). An ER model is a design or blueprint
of a database that can later be implemented as a database.

Entity-relationship diagrams, also called ERDs or ER diagrams,


are flowchart-like diagrams that explain the structure of entities,
attributes, and their relationships in a database. They are mainly used for
relational database design, and can be used to troubleshooting designs.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 21 | 77
For example:
Suppose we design a school database. In this database, the student will
be an entity with attributes like address, name, id, age, etc. The address
can be another entity with attributes like city, street name, pin code, etc
and there will be a relationship between them.

Components of ER Diagram:

ER Model
Entity Attribute Relation

- Strong Entity - Key Attribute - One to one


- Weak Entity - Composite Attribute - One to many
- Multivalued Attribute - Many to one
- Derived Attribute - Many to Many

Notations of ER Model:

Sr.
Figures Symbols Description
No.

1 Rectangle Entities in ER Model

2 Ellipse Attributes in ER Model

Relationships among
3 Diamond
Entities

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 22 | 77
Attributes to Entities and
5 Line Entity Sets with other
Relationship types

Double
6 Multi-valued Attributes
Ellipse

Double
7 Weak Entity
Rectangle

Entity:
An Entity may be an object with a physical existence – a particular
person, car, house, or employee – or it may be an object with a conceptual
existence – a company, a job, or a university course

Entity Set:
An Entity is an object of Entity Type and a set of all entities is called an
entity set. For Example, E1 is an entity having Entity Type Student and
the set of all students is called Entity Set.

In ER diagram, Entity Type is represented as:

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 23 | 77
1. Strong Entity:
A Strong Entity is a type of entity that has a key Attribute. Strong Entity
does not depend on other Entity in the Schema. It has a primary key, that
helps in identifying it uniquely, and it is represented by a rectangle. These
are called Strong Entity Types.

2. Weak Entity:
An Entity type has a key attribute that uniquely identifies each entity in
the entity set. But some entity type exists for which key attributes can’t
be defined. These are called Weak Entity types.

For Example:
A company may store the information of dependents (Parents, Children,
Spouse) of an Employee. But the dependents don’t have existed without
the employee. So Dependent will be a Weak Entity Type and Employee
will be Identifying Entity type for Dependent, which means it is Strong
Entity Type.
A weak entity type is represented by a Double Rectangle. The
participation of weak entity types is always total. The relationship
between the weak entity type and its identifying strong entity type is
called identifying relationship and it is represented by a double diamond.

Figure: Strong Entity and Weak Entity

Attributes:
Attributes are the properties that define the entity type. For example,
Roll_No, Name, DOB, Age, Address, and Mobile_No are the attributes that
define entity type Student. In ER diagram, the attribute is represented by
an oval.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 24 | 77
1. Key Attribute:
The attribute which uniquely identifies each entity in the entity set is
called the key attribute. For example, Roll_No will be unique for each
student. In ER diagram, the key attribute is represented by an oval with
underlying lines.

Figure: Key Attribute

2. Composite Attribute:
An attribute composed of many other attributes is called a composite
attribute. For example, the Address attribute of the student Entity type
consists of Street, City, State, and Country. In ER diagram, the composite
attribute is represented by an oval comprising of ovals.

Figure: Composite Attribute

3. Multivalued Attribute:
An attribute consisting of more than one value for a given entity. For
example, Phone_No (can be more than one for a given student). In ER
diagram, a multivalued attribute is represented by a double oval.

Figure: Multivalued Attribute

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 25 | 77
4. Derived Attribute:
An attribute that can be derived from other attributes of the entity type is
known as a derived attribute. e.g.; Age (can be derived from DOB). In ER
diagram, the derived attribute is represented by a dashed oval.

Figure: Derived Attribute

The Complete Entity Type Student with its Attributes can be represented
as:

Figure: Entity and Attributes

Cardinality:

The number of times an entity of an entity set participates in a


relationship set is known as cardinality. Cardinality can be of different
types:

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 26 | 77
Sr. Cardinality
Description Sets
No. Type

When each entity in each


entity set can take part
only once in the
1 One-to-One relationship, the cardinality
is one-to-one. The total
number of tables that can
be used in this is 2.

In one-to-many mapping as
well where each entity can
be related to more than one
relationship and the total
2 One-to-Many number of tables that can
be used in this is 2. total
number of tables that can
used is 3.

When entities in one entity


set can take part only once
in the relationship set and
entities in other entity sets
can take part more than
3 Many-to-One
once in the relationship
set, cardinality is many to
one. The total number of
tables that can be used in
this is 3.

When entities in all entity


sets can take part more
than once in the
Many-to-
4 relationship cardinality is
Many
many to many. the total
number of tables that can
be used in this is 3.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 27 | 77
How to Draw ER Diagram?

• The very first step is Identifying all the Entities, and place them in a
Rectangle, and labeling them accordingly.
• The next step is to identify the relationship between them and pace
them accordingly using the Diamond, and make sure that,
Relationships are not connected to each other.
• Attach attributes to the entities properly.
• Remove redundant entities and relationships.
• Add proper colors to highlight the data present in the database.

Enhanced Entity Relationship:

The enhanced entity–relationship (EER) model (or extended entity–


relationship model) in computer science is a high-level or conceptual data
model incorporating extensions to the original entity–relationship (ER)
model, used in the design of databases.

The Extended Entity-Relationship Model is a more complex and high-level


model that extends an E-R diagram to include more types of abstraction,
and to more clearly express constraints. All of the concepts contained
within an E-R diagram are included in the EE-R model, along with
additional concepts that cover more semantic information. These
additional concepts include generalization/specialization, union,
inheritance, and subclass/super class.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 28 | 77
CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What ER and EER Diagram?


2. What are different types of Cardinality?
3. What is Difference between ER and EER Diagram?
4. What are different components of ER Model

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 29 | 77
GROUP B Design and implement a database (for assignment no
ASSIGNMENT NO.2 1) using DDL statements and apply normalization on
them.
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 02
AIM:
Design and implement a database (for assignment no 1) using DDL
statements and apply normalization on them.

PREREQUISITE:

1. Data Structures
2. Software Engineering Principles

OBJECTIVES:
1. To study Data Definition Language with SQL Commands.
2. To understand concept of normalization.

THEORY:
What is SQL?

SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS). It is a
standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables. All the
RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use
SQL as their standard database language.
SQL allows users to query the database in a number of ways, using
English-like statements.

What is SQL Commands?

SQL commands are the instructions used to communicate with a


database to perform tasks, functions, and queries with data. SQL
commands can be used to search the database and to do other functions

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 30 | 77
like creating tables, adding data to tables, modifying data, and dropping
tables.

SQL Rules:

SQL follows the following rules:

• Structure query language is not case sensitive. Generally, keywords


of SQL are written in uppercase.
• Statements of SQL are dependent on text lines. We can use a single
SQL statement on one or multiple text line.
• Using the SQL statements, you can perform most of the actions in a
database.
• SQL depends on tuple relational calculus and relational algebra.

What is DDL:

DDL is an abbreviation of Data Definition Language. The DDL Commands


in Structured Query Language are used to create and modify the schema
of the database and its objects. The syntax of DDL commands is
predefined for describing the data. The commands of Data Definition
Language deal with how the data should exist in the database.

DDL or Data Definition Language actually consists of the SQL commands


that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the
structure of database objects in the database. DDL is a set of SQL
commands used to create, modify, and delete database structures but not
data.

Following are the five DDL commands in SQL:

1. CREATE Command
2. DROP Command
3. ALTER Command
4. TRUNCATE Command
5. RENAME Command

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 31 | 77
1. CREATE command:
CREATE command is used to create databases, tables,
Description:
triggers and other database objects.
❖ Syntax to Create a Database:
CREATE Database Database_Name;
❖ Syntax to create a new table:
CREATE TABLE table_name
Syntax: (
column_Name1 data_type ( size of the column ) ,
column_Name2 data_type ( size of the column) ,
...
column_NameN data_type ( size of the column )
);

2. DROP command:
DROP command is used to delete/remove the database
Description: objects from the SQL database.
❖ Syntax to remove a Database:
DROP Database Database_Name;
❖ Syntax to remove a table:
Syntax: DROP TABLE Table_Name;
❖ Syntax to remove an index:
DROP INDEX Index_Name;

3. ALTER command:
ALTER command changes or modifies the existing
structure of the database, and it also changes the
Description: schema of database objects.
We can also add and drop constraints of the table using
the ALTER command.
❖ Syntax to add new field in table :
ALTER TABLE table_Name ADD col_name col_definition;
❖ Syntax to remove existing column from table:
Syntax: ALTER TABLE table_name DROP col_name_1, col_name_2;
❖ Syntax to modify the column of the table:
ALTER TABLE table_name MODIFY(col_name col_datatype
(size));

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 32 | 77
4. TRUNCATE command:
TRUNCATE is another DDL command which deletes or
removes all the records from the table.
Description:
This command also removes the space allocated for
storing the table records.
❖ Syntax:
Syntax:
TRUNCATE Table_Name;

5. RENAME command:

RENAME is a DDL command which is used to change the


Description:
name of the database table.

❖ Syntax:
Syntax:
RENAME TABLE Old_Table_Name To New_Table_Name;

What is Normalization?

Normalization is the process of organizing data in a database. It


includes creating tables and establishing relationships between those
tables according to rules designed both to protect the data and to make
the database more flexible by eliminating redundancy and inconsistent
dependency Normalization is used to minimize the redundancy from a
relation or set of relations.
It is also used to eliminate undesirable characteristics like
Insertion, Update, and Deletion Anomalies.
Normalization divides the larger table into smaller and links them using
relationships. The normal form is used to reduce redundancy from the
database table.

Why do we need Normalization?

The main reason for normalizing the relations is removing these


anomalies. Failure to eliminate anomalies leads to data redundancy and
can cause data integrity and other problems as the database grows.
Normalization consists of a series of guidelines that helps to guide you in
creating a good database structure.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 33 | 77
Advantages of Normalization:

1. Normalization helps to minimize data redundancy.


2. Greater overall database organization.
3. Data consistency within the database.
4. Much more flexible database design.
5. Enforces the concept of relational integrity.

Disadvantages of Normalization:

1. You cannot start building the database before knowing what the
user needs.
2. The performance degrades when normalizing the relations to higher
normal forms, i.e., 4NF, 5NF.
3. It is very time-consuming and difficult to normalize relations of a
higher degree.
4. Careless decomposition may lead to a bad database design, leading
to serious problems.
Data modification anomalies:

Insertion Anomaly Deletion Anomaly Updation Anomaly

Insertion Anomaly The delete anomaly The update anomaly


refers to when one refers to the situation is when an update of
cannot insert a new where the deletion of a single data value
tuple into a data results in the requires multiple rows
relationship due to unintended loss of of data to be updated.
lack of data. some other important
data.

Types of Normal Forms:

Normalization works through a series of stages called Normal


forms. The normal forms apply to individual relations. The relation is said
to be in particular normal form if it satisfies constraints.

Sr. Normal
Description
No Form
1 1NF • A relation is in 1NF if it contains an atomic value.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 34 | 77
• Eliminating repeating groups.
• A relation will be in 2NF if it is in 1NF and all non-
key attributes are fully functional dependent on
2 2NF
the primary key.
• Eliminate partial functional dependency
• A relation will be in 3NF if it is in 2NF and no
3 3NF transition dependency exists.
• Eliminate transitive dependency.
• A stronger definition of 3NF is known as Boyce
4 BCNF
Codd's normal form.
• A relation will be in 4NF if it is in Boyce Codd's
5 4NF normal form and has no multi-valued dependency.
• Eliminate multi-valued dependency
• A relation is in 5NF. If it is in 4NF and does not
contain any join dependency, joining should be
6 5NF
lossless.
• Eliminate join dependency

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What are different types DDL commands.


2. Explain Truncate command with example.
3. Explain Rename command with example.
4. What is normalization in DBMS?
5. Explain First Normal(1NF) form with example.
6. Explain Second Normal(2NF) form with example.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 35 | 77
7. Explain Third Normal(3NF) form with example.
8. Explain BCNF with example.
9. Explain use of DDL commands and show it practically.
10. Explain fifth Normal form with example.

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 36 | 77
GROUP B Create Table with primary key and foreign key
ASSIGNMENT NO.3 constraints.
a. Alter table with add n modify b. Drop table
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 03
AIM:
Create Table with primary key and foreign key constraints.
a. Alter table with add n modify
b. Drop table

PREREQUISITE:
1. Data Structures
2. Software Engineering Principles

OBJECTIVES:
1. To study Primary key and foreign key constraints
2. To study alter and drop commands.

OUTCOMES:
1. Analyze database models & entity relationship models.
2. Design and implement a database schema for a given problem-
domain
3. Implement relational database systems.
4. Populate and query a database using SQL DDL / DML / DCL
commands.

THEORY:
What is Constraints?

Constraints in DBMS (Database Management Systems)


are rules or conditions that are applied to the data within a database to
ensure data integrity, consistency, and adherence to business rules. They
define limitations and requirements that the data must meet, thereby
preventing the entry of invalid or inconsistent data.
Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the table. If

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 37 | 77
there is any violation between the constraint and the data action, the
action is aborted. Constraints can be column level or table level.
Constraints can be column level or table level. Column level constraints
apply to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:

Sr.
Constraint Description
No
1 NOT NULL Ensures that a column cannot have a NULL value

2 UNIQUE Ensures that all values in a column are different


PRIMARY A combination of a NOT NULL and UNIQUE.
3
KEY Uniquely identifies each row in a table
FOREIGN Prevents actions that would destroy links between
4
KEY tables
Ensures that the values in a column satisfies a
5 CHECK
specific condition
Sets a default value for a column if no value is
6 DEFAULT
specified
CREATE Used to create and retrieve data from the database
7
INDEX very quickly

1. SQL NOT NULL Constraint:

By default, a column can hold NULL values. The NOT NULL constraint
enforces a column to NOT accept NULL values. This enforces a field to
always contain a value, which means that you cannot insert a new record,
or update a record without adding a value to this field.

SQL NOT NULL on CREATE TABLE:

The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Students" table is
created:
Example:

CREATE TABLE Students (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 38 | 77
SQL NOT NULL on ALTER TABLE:

To create a NOT NULL constraint on the "Age" column when the "Persons"
table is already created, use the following SQL:
Example:

ALTER TABLE Students


MODIFY COLUMN Age int NOT NULL;

2. SQL UNIQUE Constraint:

The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns. A PRIMARY KEY constraint
automatically has a UNIQUE constraint. However, you can have
many UNIQUE constraints per table, but only one PRIMARY KEY constraint
per table.

SQL UNIQUE Constraint on CREATE TABLE:

The following SQL creates a UNIQUE constraint on the "ID" column when
the "Students" table is created:

CREATE TABLE Students (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

To name a UNIQUE constraint, and to define a UNIQUE constraint on


multiple columns, use the following SQL syntax:

CREATE TABLE Students (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 39 | 77
CONSTRAINT UC_Student UNIQUE (ID,LastName)
);

SQL UNIQUE Constraint on ALTER TABLE:

To create a UNIQUE constraint on the "ID" column when the table is


already created, use the following SQL:

ALTER TABLE Students


ADD UNIQUE (ID);
To name a UNIQUE constraint, and to define a UNIQUE constraint on
multiple columns, use the following SQL syntax:

ALTER TABLE Students


ADD CONSTRAINT UC_Student UNIQUE (ID,LastName);

DROP a UNIQUE Constraint:

To drop a UNIQUE constraint, use the following SQL:

ALTER TABLE Students


DROP INDEX UC_Student;

3. SQL PRIMARY KEY Constraint:

• The PRIMARY KEY constraint uniquely identifies each record in a


table.
• Primary keys must contain UNIQUE values, and cannot contain
NULL values.
• A table can have only ONE primary key; and in the table, this
primary key can consist of single or multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE:

The following SQL creates a PRIMARY KEY on the "ID" column when the
"Students" table is created:

CREATE TABLE Students (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 40 | 77
PRIMARY KEY (ID)
);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY
KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Students (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Student PRIMARY KEY (ID,LastName)
);

SQL PRIMARY KEY on ALTER TABLE:

To create a PRIMARY KEY constraint on the "ID" column when the table is
already created, use the following SQL:

ALTER TABLE Students


ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY


KEY constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Students


ADD CONSTRAINT PK_Student PRIMARY KEY (ID, LastName);

If you use ALTER TABLE to add a primary key, the primary key column(s)
must have been declared to not contain NULL values (when the table was
first created).

DROP a PRIMARY KEY Constraint:

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Students


DROP PRIMARY KEY;
4. SQL FOREIGN KEY Constraint:

The FOREIGN KEY constraint is used to prevent actions that would


destroy links between tables.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 41 | 77
A FOREIGN KEY is a field (or collection of fields) in one table, that refers
to the PRIMARY KEY in another table.

The table with the foreign key is called the child table, and the table with
the primary key is called the referenced or parent table.

Look at the following two tables:


Persons Table:
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20

Orders Table:
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2

Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the


"Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values
contained in the parent table.

SQL FOREIGN KEY on CREATE TABLE:

The following SQL creates a FOREIGN KEY on the "PersonID" column when
the "Orders" table is created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 42 | 77
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN


KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY on ALTER TABLE:

To create a FOREIGN KEY constraint on the "PersonID" column when the


"Orders" table is already created, use the following SQL:

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
To allow naming of a FOREIGN KEY constraint, and for defining
a FOREIGN KEY constraint on multiple columns, use the following SQL
syntax:

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint:

To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 43 | 77
CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What is constraints in DBMS?


2. Explain Entity integrity constraints with example.
3. What are different types of Integrity Constraints? Explain in detail.
4. What is primary key in DBMS?
5. Explain foreign key with example.

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 44 | 77
Perform following SQL queries on the database
created in assignment 1.
1. Implementation of relational operators in SQL
GROUP B 2. Boolean operators and pattern matching
ASSIGNMENT NO.4 3. Arithmetic operations and built in functions
4. Group functions
5. Processing Date and Time functions
6. Complex queries and set operators
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 04
AIM:
Perform following SQL queries on the database created in assignment 1.
1. Implementation of relational operators in SQL
2. Boolean operators and pattern matching
3. Arithmetic operations and built in functions
4. Group functions
5. Processing Date and Time functions
6. Complex queries and set operators

PREREQUISITE:
1. Data Structures
2. Operators

OBJECTIVES:
1. To understand the relational operators, Boolean operators and
pattern matching & Arithmetic operations.
2. To Understand the built in functions, Group functions, Date and
Time functions, Complex queries and set operators.

THEORY:
SQL commands are instructions. It is used to communicate
with the database. It is also used to perform specific tasks, functions, and
queries of data.

BOOLEAN OPERATOR

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 45 | 77
A Boolean is a universal data type which stores true or false values. It is
used when we define a variable in a column of the table.
For instance, a customer wants a list of all the red cars. So, we can find
this using the BOOLEAN operator as given in the below table −

Here, IS_RED is the BOOLEAN column that returns either TRUE or


FALSE values based on the color of the cars.
Boolean in MySQL
MySQL provides various options for handling Boolean data. You can use
BOOL, BOOLEAN, or TINYINT to represent Boolean values.
When you use BOOL or BOOLEAN, MySQL internally converts them into
TINYINT. Similar to many programming languages like PHP, C, and C++,
MySQL represents the TRUE literal as 1 and the FALSE literal as 0.
Example
Here, we are creating a table 'CARS' with column BOOLEAN. The query to
create a table is as follows –
CREATE CREATE TABLE CARS( ID INT NOT NULL , Name VARCHAR(150
), IsRed BOOLEAN);
In the above example, a table is created with a BOOLEAN column IsRed.
You can insert TRUE as 1 or FALSE as 0 in this column to represent the
corresponding Boolean values.

SQL Comparison Keywords:


There are other comparison keywords available in sql which are used to
enhance the search capabilities of a sql query. They are "IN",
"BETWEEN...AND", "IS NULL", "LIKE".

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 46 | 77
Comparision
Description
Operators

LIKE column value is similar to specified character(s).

IN column value is equal to any one of a specified set of values.

column value is between two values, including the end values


BETWEEN...AND
specified in the range.

IS NULL column value does not exist.

SQL LIKE Operator:


The LIKE operator is used to list all rows in a table whose column
values match a specified pattern. It is useful when you want to search
rows to match a specific pattern, or when you do not know the entire
value. For this purpose we use a wildcard character '%'.
For example:
To select all the students whose name begins with 'S'
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE 'S%';

For example:
to display all the names with 'a' second character,
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE '_a%';

SQL BETWEEN ... AND Operator


The operator BETWEEN and AND, are used to compare data for a range of
values.
For Example: to find the names of the students between age 10 to 15
years, the query would be like,
SELECT first_name, last_name, age
FROM student_details
WHERE age BETWEEN 10 AND 15;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 47 | 77
SQL IN Operator:
The IN operator is used when you want to compare a column with more
than one value. It is similar to an OR condition.
For example: I
f you want to find the names of students who are studying either Maths
or Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject IN ('Maths', 'Science');

SQL IS NULL Operator:


A column value is NULL if it does not exist. The IS NULL operator is used
to display all the rows for columns that do not have a value.
For Example: If you want to find the names of students who do not
participate in any games, the query would be as given below
SELECT first_name, last_name
FROM student_details
WHERE games IS NULL

There would be no output as we have every student participate in a


game in the table student_details, else the names of the students who
do not participate in any games would be displayed.

SQL AGGREGATE FUNCTIONS

In general, aggregation is a consideration of a collection of objects that


are bound together as a single entity. SQL provides a set of aggregate
functions that perform operations on all the entities of the column of
a table considering them as a single unit. Following are the SQL
aggregate functions −

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 48 | 77
Sr. Function & Description
No.

APPROX_COUNT_DISTINCT()
1 Returns the approximate number of rows with distinct
expression values.

AVG()
2 Returns the average of the fields in a particular column that
has only numeric values.

CHECKSUM_AGG()
3
Returns the checksum value.

COUNT_BIG()
4 Returns the count of the number of items or rows selected by
the select statement.

COUNT()
5 Returns the number of non-NULL values in a particular
column.

GROUPING()
6 Returns whether the specified column expression in a group
by list is aggregate or not.

GROUPING_ID()
7
Returns the level of grouping.

MAX()
8 Returns the maximum value among the fields in a particular
column.

MIN()
9
Returns the minimum value among the fields in a particular
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 49 | 77
column.

STDEV()
10 Returns the statistical standard deviation of the fields
(numerical values) in a particular column.

STDEVP()
11 Returns the population standard deviation for the fields
(numerical values) in a particular column.

SUM()
12 Returns the sum of all the fields (numeric) in a particular
column.

VAR()
13 Returns the statistical standard variance of the fields
(numerical values) in a particular column.

VARP()
14 Returns the population standard variance of the fields
(numerical values) in a particular column.

SQL DATE/TIME FUNCTIONS

Getting the current Date & Time:

• CURDATE() – Return the current date. ( synonyms: CURRENT_DATE()


& CURRENT_DATE).
• CURRENT_TIME – Return the current time ( synonyms:
CURRENT_TIME() & CURTIME() ).
• NOW() – Return the current date and time ( synonyms:
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP, LOCALTIME(),
LOCALTIMESTAMP()).
• SYSDATE() – Return the time at which it executes.
• UTC_TIMESTAMP() – Return the current UTC date and time.
• UTC_DATE() – Return the current UTC date.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 50 | 77
• UTC_TIME() – Return the current UTC time.

Calculating Date and Time

• ADDTIME() – Add a time interval to a time value or datetime value.


• DATE_ADD() – Add a time value to a date (synonyms: ADDDATE()).
• DATE_SUB() – Subtract a time value (interval) from a date.
• DATEDIFF() – Return the difference in days of two date values.
• TIMEDIFF() – Return the difference of two time values.
• TIMESTAMPADD() – Add or subtract an interval from a timestamp or
date.
• TIMESTAMPDIFF() – Return the difference between two timestamp values.
• TIME_TO_SEC() – Return the number of seconds from a time argument.
• TO_DAYS() – Return a day number (the number of days since year 0) from
a given date.

Converting Functions

• CONVERT_TZ() – Convert a datetime value from one time zone to another.


• FROM_DAYS() – Convert a numeric day count into a date.
• STR_TO_DATE() – Convert a string to date.
• FROM_UNIXTIME() – Convert UNIX timestamps into a readable date and
time format.
• UNIX_TIMESTAMP() – Convert a datetime to a UNIX timestamp.

Formatting Date & Time functions:

• DATE_FORMAT() – Return a string representation of a date based on a


format.
• TIME_FORMAT() – Return a string representation of a time based on a
format.
• GET_FORMAT() – Return a format string for a date, time, datetime, or
timestamp.

Extracting Date & Time Functions

The extraction functions allow you to extract date and time components
from a date and time.

• DATE() – Extract the date component from a date.


• EXTRACT() – Extract a component of a date.
• YEAR() – Return the year component of a date.
• YEARWEEK() – Return the year and week for a date.
• QUARTER() – Return the quarter of the year for a date.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 51 | 77
• MONTH() – Return the month component of a date.
• WEEK() – Return the week component of a date.
• WEEKDAY() – Return the weekday index of a date.
• WEEKOFYEAR() – Return the calendar week of the date (1-53) –
equivalent to WEEK(date, 3).
• DAY() – Return the day of the month for a specific date (1-31).
DAYOFMONTH is the synonym for DAY.
• DAYOFYEAR() – Return the day of the year (1-366).
• DAYOFWEEK() – Return the day of the week (1-7).
• HOUR() – Return the hour for a time.
• MINUTE() – Return the minute for a time.
• SECOND() – Return the second for a time.
• LAST_DAY() – Return an integer that represents the last day of the month
for a specific date

Getting Month & Day Names

This section shows you how to use functions to get the month and day
names.

• DAYNAME() – Return the name of the day for a specific date.


• MONTHNAME() – Return the name of the month for a specific date.

Creating Date & Time Functions

• MAKEDATE() – create a date based on a given year and the number of


days.
• MAKETIME() – create a time based on hour, minute, and second.

Handling Period Functions

This section covers the function that manipulates the periods in the
format YYMM or YYMMMM.

• PERIOD_ADD() – add a number of months to a period in the format YYMM


or YYMMMM.
• PERIOD_DIFF() – calculate the difference in months of two periods
represented in the format YYMM or YYYYMM.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 52 | 77
CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What are operators in DBMS?


2. Explain Date function in DBMS.
3. Explain Arithmetic Operators and Boolean operators in DBMS with
example.

OUTPUT:
(Attach Screenshots of your output in sequence

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 53 | 77
Execute DDL/DML statements which demonstrate
the use of views. Update the base table using its
GROUP B
corresponding view. Also consider restrictions on
ASSIGNMENT NO.5 updatable views and perform view creation from
multiple tables.
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 05

AIM:
Execute DDL/DML statements which demonstrate the use of views.
Update the base table using its corresponding view. Also consider
restrictions on updatable views and perform view creation from multiple
tables.

PREREQUISITE:
1. Data Structures
2. Software Engineering Principles

OBJECTIVES:
1. To understand DDL and DML commands.
2. To understand views and its use.

THEORY:
What is View?

View are virtual table obtained as a result of a query in SQL i.e.


Structured Query Language. Whenever the end-user requests the data
according to specified needs rather than complete information of the
table. Views in SQL are kind of virtual tables. A view also has rows and
columns as they are in a real table in the database. We can create a view
by selecting fields from one or more tables present in the database. A
View can either have all the rows of a table or specific rows based on
certain condition.
Views in SQL are considered as a virtual table. A view also contains rows
and columns. To create the view, we can select the fields from one or
more tables present in the database. A view can either have specific rows
based on certain condition or all the rows of a table.
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 54 | 77
Advantages of View:

1. Complexity: Views help to reduce the complexity. Different views


can be created on the same base table for different users.
2. Security: It increases the security by excluding the sensitive
information from the view.
3. Query Simplicity: It helps to simplify commands from the user. A
view can draw data from several different tables and present it as a
single table.
4. Consistency: A view can present a consistent, unchanged image of
the structure of the database. Views can be used to rename the
columns without affecting the base table.
5. Data Integrity: If data is accessed and entered through a view, the
DBMS can automatically check the data to ensure that it meets the
specified integrity constraints.
6. Storage Capacity: Views take very little space to store the data.
7. Logical Data Independence: View can make the application and
database tables to a certain extent independent.

Disadvantages of View:

The DML statements which can be performed on a view created using


single base table have certain restrictions are:
1. You cannot INSERT if the base table has any not null column that
do not appear in view.
2. You cannot INSERT or UPDATE if any of the column referenced in
the INSERT or UPDATE contains group functions or columns
defined by expression.
3. You can't execute INSERT, UPDATE, DELETE statements on a view
if with read only option is enabled.
4. You can't be created view on temporary tables.
5. You cannot INSERT, UPDATE, DELETE if the view contains group
functions GROUP BY, DISTINCT or a reference to a psuedocolumn
rownum.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 55 | 77
Syntax:

CREATE VIEW view_name AS


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

Where
view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows

Sample table:

Consider the StudentDetails table having the following records:

S_ID NAME ADDRESS


1 Harsh Kolkata
2 Ashish Durgapur
3 Pratik Delhi
4 Dhanraj Bihar
5 Ram Rajastan

Consider the StudentMarks table having the following records:

ID NAME MARKS AGE


1 Harsh 90 19
2 Suresh 50 20
3 Pratik 80 19
4 Dhanraj 95 21
5 Ram 85 18

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 56 | 77
A. Creating View:

Example:

1. Creating View from a single table:

a. Create a View named DetailsView from the table StudentDetails.


Query:
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM
StudentDetails WHERE S_ID < 5;

To see the data in the View, we can query the view in the same manner
as we query a table.

Query:

SELECT * FROM DetailsView;

Output:

NAME ADDRESS
Harsh Kolkata
Suresh Durgapur
Pratik Delhi
Pratik Delhi
Dhanraj Bihar

b. Create view named StudentNames from the table StudentDetails.

Query:

CREATE VIEW StudentNames AS SELECT S_ID, NAME


FROM StudentDetails ORDER BY NAME;

To see the data in the View, we can query the view in the same manner
as we query a table.

Query:
SELECT * FROM StudentNames;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 57 | 77
S_ID NAME
2 Ashish
4 Dhanraj
1 Harsh
3 Pratik
5 Ram

2. Creating View from multiple tables:


Create a View named MarksView from two tables StudentDetails and
StudentMarks. To create a View from multiple tables we can simply
include multiple tables in the SELECT statement.

Query:

CREATE VIEW MarksView As SELECT StudentDetails.NAME,


StudentDetails.ADDRESS, StudentMarks.MARKS FROM
StudentDetails, StudentMarks WHERE StudentDetails.NAME =
StudentMarks.NAME;

To display data of View MarksView:

Query:
SELECT * FROM MarksView;

Output:

NAME ADDRESS MARKS


Harsh Kolkata 90
Pratik Delhi 80
Dhanraj Bihar 95
Ram Rajastan 85

B. Listing All Views in a database:

We can list View using the SHOW FULL TABLES statement or using the
information_schema table. A View can be created from a single table or
multiple tables.
Syntax (Using SHOW FULL TABLES):
use "database_name";
show full tables where table_type like "%VIEW";

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 58 | 77
Syntax (Using information_schema) :

select * from information_schema.views where table_schema =


"database_name";
OR
select table_schema,table_name,view_definition from
information_schema.views where table_schema = "database_name";

C. Deleting Views:

SQL allows us to delete an existing View. We can delete or drop a View


using the DROP statement.
Syntax:
DROP VIEW view_name;

view_name: Name of the View which we want to delete.

For example:
If we want to delete the View MarksView, we can do this as: DROP VIEW
MarksView;

D. Updating Views:
There are certain conditions needed to be satisfied to update a view. If
any one of these conditions is not met, then we will not be allowed to
update the view.

1. The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex
queries.
5. The view should be created from a single table. If the view is
created using multiple tables then we will not be allowed to update
the view.

We can use the CREATE OR REPLACE VIEW statement to add or remove


fields from a view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,column2,..
FROM table_name
WHERE condition;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 59 | 77
For example:

If we want to update the view MarksView and add the field AGE to this
View from StudentMarks Table, we can do this as
CREATE OR REPLACE VIEW MarksView AS SELECT
StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE FROM StudentDetails, StudentMarks WHERE
StudentDetails.NAME = StudentMarks.NAME;

If we fetch all the data from MarksView now as:

SELECT * FROM MarksView;

Output:

NAME ADDRESS MARKS AGE


Harsh Kolkata 90 19
Pratik Delhi 80 19
Dhanraj Bihar 95 21
Ram Rajastan 85 18

Uses of a View:

A good database should contain views due to the given reasons:

1. Restricting data access – Views provide an additional level of table


security by restricting access to a predetermined set of rows and
columns of a table.
2. Hiding data complexity – A view can hide the complexity that
exists in multiple tables join.
3. Simplify commands for the user – Views allow the user to select
information from multiple tables without requiring the users to
actually know how to perform a join.
4. Store complex queries – Views can be used to store complex
queries.
5. Rename Columns – Views can also be used to rename the columns
without affecting the base tables provided the number of columns
in view must match the number of columns specified in select
statement. Thus, renaming helps to hide the names of the
columns of the base tables.
6. Multiple view facility – Different views can be created on the same
table for different users.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 60 | 77
CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What is View in DBMS?


2. What is use of View ?
3. How to create View in MySQL?
4. What is difference between view and table?
5. What is the purpose of a view?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 61 | 77
Write and execute PL/SQL stored procedure and
GROUP C
function to perform a suitable task on the
ASSIGNMENT NO.1 database. Demonstrate its use.
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 01

AIM:
Write and execute PL/SQL stored procedure and function to perform a
suitable task on the database. Demonstrate its use.

PREREQUISITE:
1. Basic Knowledge of procedure and functions.
2. Knowledge of SQL queries.

OBJECTIVES:
1. To understand Concept of PL/SQL stored procedure and function
and its use.

THEORY:
What is PL/SQL?

PL/SQL is a block structured language that enables developers to


combine the power of SQL with procedural statements. All the statements
of a block are passed to oracle engine all at once which increases
processing speed and decreases the traffic.
PL/SQL is a block structured language that can have multiple blocks in
it. PL/SQL is a block structured language. The programs of PL/SQL are
logical blocks that can contain any number of nested sub-blocks. Pl/SQL
stands for "Procedural Language extension of SQL" that is used in Oracle.
PL/SQL is integrated with Oracle database (since version 7). The
functionalities of PL/SQL usually extended after each release of Oracle
database. Although PL/SQL is closely integrated with SQL language, yet it
adds some programming constraints that are not available in SQL.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 62 | 77
Basics of PL/SQL:

• PL/SQL stands for Procedural Language extensions to the


Structured Query Language (SQL).
• PL/SQL is a combination of SQL along with the procedural features
of programming languages.
• Oracle uses a PL/SQL engine to processes the PL/SQL statements.
• PL/SQL includes procedural language elements like conditions and
loops. It allows declaration of constants and variables, procedures
and functions, types and variable of those types and triggers.
Features of PL/SQL:

1. PL/SQL is basically a procedural language, which provides the


functionality of decision making, iteration and many more features
of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single
command.
3. One can create a PL/SQL unit such as procedures, functions,
packages, triggers, and types, which are stored in the database for
reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in
PL/SQL block known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware
or operating system where Oracle is operational.
6. PL/SQL Offers extensive error checking.
7. PL/SQL is tightly integrated with SQL.
8. It offers numerous data types.
9. It offers a variety of programming structures.
10. It supports structured programming through functions and
procedures.
11. It supports object-oriented programming.
12. It supports the development of web applications and server pages.

Syntax of PL/SQL:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 63 | 77
Sr.
Section Description
No.
This section starts with the keyword DECLARE. It is
an optional section and defines all variables, cursors,
1 Declarations
subprograms, and other elements to be used in the
program.
This section is enclosed between the
keywords BEGIN and END and it is a mandatory
section. It consists of the executable PL/SQL
Executable
2 statements of the program. It should have at least
Commands
one executable line of code, which may be just
a NULL command to indicate that nothing should be
executed.
This section starts with the keyword EXCEPTION.
Exception
3 This optional section contains exception(s) that
Handling
handle errors in the program.

Example:

DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/

The end; line signals the end of the PL/SQL block. To run the code from
the SQL command line, you may need to type / at the beginning of the
first blank line after the last line of the code. When the above code is
executed at the SQL prompt, it produces the following result

Hello World

PL/SQL procedure successfully completed

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 64 | 77
The PL/SQL Delimiters:

A delimiter is a symbol with a special meaning. Following is the list of


delimiters in PL/SQL:
Sr.
Delimiter Description
No.
Addition, subtraction/negation, multiplication,
1 +, -, *, /
division.
2 % Attribute indicator
3 ' Character string delimiter
4 . Component selector
5 (,) Expression or list delimiter
6 : Host variable indicator
7 , Item separator
8 " Quoted identifier delimiter
9 = Relational operator
10 @ Remote access indicator
11 ; Statement terminator
12 := Assignment operator
13 => Association operator
14 || Concatenation operator
15 ** Exponentiation operator
16 <<, >> Label delimiter (begin and end)
17 /*, */ Multi-line comment delimiter (begin and end)
18 -- Single-line comment indicator
19 .. Range operator
20 <, >, <=, >= Relational operators
<>, '=, ~=,
21 Different versions of NOT EQUAL
^=

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 65 | 77
QUESTIONS:
Write the answers of following questions.

1. What is PL/SQL Block in DBMS?


2. What is use procedural language ?
3. How to write PL/SQL in MySQL?
4. What is difference between SQL and PL/SQL?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 66 | 77
GROUP C Write and execute suitable database triggers.
ASSIGNMENT NO.2 Consider row level and statement level triggers.
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 02
AIM:
Write and execute suitable database triggers. Consider row level and
statement level triggers.

PREREQUISITE:

1. Knowledge of MySQL Databases

OBJECTIVES:
1. To understand the concept of database MySQL Trigger

THEORY:
Introduction to MYSQL Trigger

What is a Trigger?

A trigger is a MYSQL block structure which is fired when a DML


statements like Insert, Delete, Update is executed on a database table. A
trigger is triggered automatically when an associated DML statement is
executed.

Types of triggers:

There are two types of triggers based on the which level it is triggered.
1. Row level trigger: An event is triggered for each row updated,
inserted or deleted.
2. Statement level trigger: An event is triggered for each sql statement
executed.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 67 | 77
Trigger Execution Hierarchy:

The following hierarchy is followed when a trigger is fired.


1. BEFORE statement trigger fires first.
2. Next BEFORE row level trigger fires, once for each row affected.
3. Then AFTER row level trigger fires once for each affected row. This
events will alternates between BEFORE and AFTER row level
triggers.
4. Finally the AFTER statement level trigger fires.

Syntax of Trigger

The Syntax for creating a trigger is:

CREATE TRIGGER trigger_name


{BEFORE | AFTER | }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition) BEGIN
--- sql statements
END;

• CREATE TRIGGER trigger_name - This clause creates a trigger with


the given name or overwrites an existing trigger with the same name.

• {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what


time should the trigger get fired. i.e for example: before or after
updating a table. INSTEAD OF is used to create a trigger on a view.
before and after cannot be used to create a trigger on a view.

• {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines


the triggering event. More than one triggering events can be used
together separated by OR keyword. The trigger gets fired at all the
specified triggering event.

• [OF col_name] - This clause is used with update triggers. This clause
is used when you want to trigger an event only when a specific
column is updated.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 68 | 77
• CREATE [OR REPLACE ] TRIGGER trigger_name - This clause
creates a trigger with the given name or overwrites an existing
trigger with the same name.

• [ON table_name] - This clause identifies the name of the table or


view to which the trigger is associated.

• [REFERENCING OLD AS o NEW AS n] - This clause is used to


reference the old and new values of the data being changed. By
default, you reference the values as

• :old.column_name or :new.column_name. The reference names can


also be changed from old (or new) to any other user-defined name.
You cannot reference old values when inserting a record, or new
values when deleting a record, because they do not exist.

• [FOR EACH ROW] - This clause is used to determine whether a


trigger must fire when each row gets affected (i.e. a Row Level
Trigger) or just once when the entire sql statement is executed (i.e.
statement level Trigger).

• WHEN (condition) - This clause is valid only for row level triggers.
The trigger is fired only for rows that satisfy the condition specified.

Trigger Examples:

Example 1:

This example is based on the following two tables:


CREATE TABLE T4 ( a INTEGER, CHAR(10));
CREATE TABLE T5 ( c CHAR(10), d INTEGER);

create a trigger that may insert a tuple into T5 when a tuple is inserted
into T4. inserts the reverse tuple into T5:

1. Create trigger as follows:

CREATE TRIGGER trig1 AFTER INSERT ON T4


FOR EACH ROW BEGIN
INSERT INTO t5 SET c = NEW.b,d = NEW.a;
END;

2. Insert values in T4.


3. Check the values in T5.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 69 | 77
Example 2:
The price of a product changes constantly. It is important to maintain
the history of the prices of the products. Create a trigger to update the
'product_price_history' table when the price of the product is updated in
the 'product' table.
Create the 'product' table and 'product_price_history' table

CREATE TABLE product_price_history


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product (product_id number(5),


product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
drop trigger if exists price_history_trigger;

CREATE TRIGGER price_history_trigger BEFORE UPDATE on


product1
FOR EACH ROW BEGIN
INSERT INTO product_price_history set product_id=old.product_id,
product_name=old.product_name,
supplier_name=old.supplier_name, unit_price=old.unit_price;
END

4. Lets update the price of a product.

UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100;

Once the above update query is executed, the trigger fires and updates
the 'product_price_history' table.

Example 3:
create table account(accno int, amount int);
Create a trigger on account table before update in new inserted amount
is less than “0” then set amount “0” else if amount is greater than 100
then set amount 100
CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 70 | 77
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END

update account set amount= -12 where accno=101

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What is trigger and curser in PL/SQL?


2. What are the types of trigger and cursor?
3. How to delete a trigger?
4. Why we write a create or replace in PL/SQL Block?
5. What is row level and statement level trigger?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 71 | 77
GROUP C
Write a PL/SQL block to implement cursors.
ASSIGNMENT NO. 3
START DATE:
SUBMISSION DATE:
SIGN. OF FACULTY:

ASSIGNMENT NO.: 03
AIM:
Write a PL/SQL block to implement cursors.

PREREQUISITE:

1. Knowledge of MySQL Databases PL/SQL

OBJECTIVES:
1. To understand the basic concept of cursors used in PL/SQL.

THEORY:
Introduction to Cursor

What is a Cursor?

Cursor is a Temporary Memory or Temporary Work Station. It is Allocated


by Database Server at the Time of Performing DML(Data Manipulation
Language) operations on the Table by the User. Cursors are used to store
Database Tables.
A Cursor is a temporary memory that is allocated by the database server
at the time of performing the Data Manipulation Language operations on
a table, such as INSERT, UPDATE and DELETE etc. It is used to retrieve
and manipulate data stored in the SQL table.
In MySQL, you cannot declare a cursor directly outside of a stored
procedure or function. Cursors are generally declared within stored
procedures, functions, or blocks of SQL code in MySQL database.
Using cursors, we can perform multiple operations on each row of a result
set, with or without returning the original data.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 72 | 77
Properties of Cursors:

Following are the properties of MySQL Cursors

• Read Only: We cannot update or modify any records in the table


using the MySQL cursors. We can just fetch and process data from
a table.
• Non-Scrollable: We can retrieve records from a table in a single
direction, i.e. from the first record or the last. We cannot move
backward or jump to a specific position within the result set.
• Asensitive Cursor: An asensitive cursor operates directly on the
actual data in the database, it does not create a copy of the data. If
any change is made to the data by other connections, it can affect
the data that the cursor is working with.

Types of cursors:

1. Implicit cursors:

• Implicit cursors are automatically created by Oracle whenever an


SQL statement is executed, when there is no Explicit cursor for the
statement. Programmers cannot control the implicit cursors and
the information in it.
• Whenever a DML statement (INSERT, UPDATE and DELETE) is
issued, an implicit cursor is associated with this statement. For
INSERT operations, the cursor holds the data that needs to be
inserted. For UPDAT E and
• DELET E operations, the cursor identifies the rows that would be
affected.

Attribute Description

Returns T RUE if an INSERT, UPDATE, or DELETE statement


affected one or more rows or a SELECT INT O statement
%FOUND
returned one or more rows.
Otherwise, it returns FALSE.
The logical opposite of %FOUND. It returns TRUE if an
INSERT, UPDATE, or DELETE statement affected no rows, or
%NOT FOUND
a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
Always returns FALSE for implicit cursors, because Oracle
%ISOPEN closes the SQL cursor automatically after executing its
associated SQL statement.

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 73 | 77
Returns the number of rows affected by an INSERT, UPDATE,
%ROWCOUNT or DELETE statement, or returned by a SELECT INT O
statement.

2. Explicit cursors:

Explicit cursors are programmer defined cursors for gaining more control
over the context area. An explicit cursor should be defined in the
declaration section of the PL/SQL Block.

The syntax for creating an explicit cursor is :

CURSOR cursor_name IS select_statement;

Working with an explicit cursor involves four steps:

1. Declaring the cursor for initializing in the memory.


2. Opening the cursor for allocating memory.
3. Fetching the cursor for retrieving data
4. Closing the cursor to release allocated memory

Declare Cursor Statement:

In MySQL we can declare a cursor using the DECLARE statement and


associate it with a SELECT statement to retrieve records from a database
table.
However, this SELECT statement associated with a cursor does not use
the INTO clause, as it's purpose is to fetch and process rows rather than
assigning values to variables.

Syntax:

Following is the syntax to declare a cursor in MySQL database:

DECLARE cursor_name CURSOR FOR select_statement;

Fetch Cursor Statement:

Then, we can use the FETCH statement to retrieve the current row
pointed by the cursor, and with each FETCH, the cursor moves to the
next row in the result set. This allows us to process each row one by one.
Syntax:

Following is the syntax to fetch a cursor in MySQL database −


FETCH cursor_name INTO variable_list;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 74 | 77
Close Cursor Statement:

Once all the rows are fetched, we must close the cursor to release the
memory associated with it. We can do this using the CLOSE statement.
Syntax:

Following is the syntax to close a cursor in MySQL database −

CLOSE cursor_name;

Example:

Assume we have created a table with the name CUSTOMERS using


the CREATE TABLE statement as follows:

CREATE TABLE CUSTOMERS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Now, let us insert some records into the CUSTOMERS table using
the INSERT statement as follows:

INSERT INTO CUSTOMERS VALUES


(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 );

Now, we will create a backup table named 'CUSTOMERS_BACKUP' to


store customer data:

CREATE TABLE CUSTOMERS_BACKUP (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
PRIMARY KEY (ID)
);

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 75 | 77
Here, we are creating a stored procedure named FetchCustomers to fetch
customer names from the CUSTOMERS table and inserting them one by
one into the BACKUP table. We are using a cursor to iterate through the
rows and a handler to detect the end of the result-set, ensuring all names
are processed –

DELIMITER //
CREATE PROCEDURE FetchCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE customer_id INT;
DECLARE customer_name VARCHAR(255);
DECLARE auto_id INT;

-- Declare cursor
DECLARE MY_CURSOR CURSOR FOR
SELECT id, name FROM CUSTOMERS;

-- Declare exit handler


DECLARE CONTINUE HANDLER FOR NOT FOUND SET done =
TRUE;

-- Open cursor
OPEN MY_CURSOR;

-- Fetch and insert rows


read_loop: LOOP
FETCH MY_CURSOR INTO customer_id, customer_name;
IF done = 1 THEN
LEAVE read_loop;
END IF;

-- Insert the fetched data into the backup table


INSERT INTO customers_backup VALUES (customer_id,
customer_name);

-- Get the last auto-generated ID used in the insertion


SET auto_id = LAST_INSERT_ID();
END LOOP;

-- Close cursor
CLOSE MY_CURSOR;

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 76 | 77
END //
DELIMITER ;

Once we create the procedure successfully, we can execute it using the


CALL statement as shown below –
CALL FetchCustomers();

You can verify the contents of the CUSTOMERS_BACKUP table using the
SELECT statement as shown below −

SELECT * FROM CUSTOMERS_BACKUP;

The contents of the table would be –

ID NAME
1 Ramesh
2 Khilan
3 Kaushik
4 Chaitali

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________

QUESTIONS:
Write the answers of following questions.

1. What is curser in PL/SQL?


2. What are the types of cursor?
3. What is difference between Implicit cursor & Explicit Cursor?

OUTPUT:
(Attach Screenshots of your output in sequence)

D e p a r t m e n t o f I n f o r m a t i o n T e c h n o l o g y P a g e 77 | 77

You might also like