0% found this document useful (0 votes)
39 views115 pages

DMS Notes

The document provides an overview of database systems, including definitions of data, databases, and DBMS, along with their purposes and advantages over file processing systems. It discusses the three-level architecture of DBMS, the concepts of schema and instance, and the importance of data independence. Additionally, it highlights various applications of DBMS across different sectors and outlines the differences between file processing systems and DBMS.

Uploaded by

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

DMS Notes

The document provides an overview of database systems, including definitions of data, databases, and DBMS, along with their purposes and advantages over file processing systems. It discusses the three-level architecture of DBMS, the concepts of schema and instance, and the importance of data independence. Additionally, it highlights various applications of DBMS across different sectors and outlines the differences between file processing systems and DBMS.

Uploaded by

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

Chapter –I Database System Concept

1.1 Concept of Data, Database, DBMS

Data: - user input to the system. User give input in any format such as Text, image, alpha numeric etc.
using input devices.

Record:-Collections of interrelated data.

Table:-It is collection of interrelated Records.(collection of rows and columns)

Database: - The collection of inter related tables is called as database.

DBMS: - The database system is collection of interrelated data and the set of programs to operate on it
(which manages this data). It is system software used to do various operation on data and rules to do
various operation (data manipulation) is called DBMS (Database management system)

Ex;- Oracle, SQL Server, MySQL, dBASE, MS-Access, PostgreSQL , MariaDB , FoxPro etc.

Data manipulation:-Various operation can be done by the user on data such as insert, update, delete,
searching data is call as data manipulation

1.2 Purpose of Database Systems

The primary goal of a DBMS is to provide a way to store and retrieve database information that is both
convenient and efficient. By data, we mean known facts that can be recorded and that have implicit
meaning.

Organizations use large amounts of data. A database management system (DBMS) is a software tool that
makes it possible to organize data in a database.

Database systems are designed to manage large bodies of information. Management of data involves both
defining structures for storage of information and providing mechanisms for the manipulation of
information. In addition, the database system must ensure the safety of the information stored, despite
system crashes or attempts at unauthorized access. If data are to be shared among several users, the
system must avoid possible anomalous results.

1.2.1 File Processing System

In Computer Science, File Processing System (FPS) is a way of storing, retrieving and manipulating data
which is present in various files. Files are used to store various documents. All files are grouped based on
their categories. The file names are very related to each other and arranged properly to easily access the
files. In file processing system, if one needs to insert, delete, modify, store or update data, one must know
the entire hierarchy of the files.
In earlier days, data was stored manually, using pen and paper but after computer was discovered, the same
task could be done by using files. A computer File is a resource which uniquely records data, in a storage
device in a computer. There are various formats in which data can be stored. e.g. Text files can be stored in
.txt format while pictures can be stored in .png format etc.

In case of computer files, data about data (metadata) can be stored in different lines, separated by spaces,
commas or tab to resemble tables. Each file is placed in relevant folders for the ease of access.

It is a computer based system in which all the information is stored in various computer files.

//////////for more details see- https://www.tutorialcup.com/dbms/file-processing-system.htm ///

1.2.2 Disadvantages of file processing system: 4marks

1. Data redundancy. (Repetition/duplication)

2. Data Inconsistency

3. Difficulty in data sharing

4 .Data dependence

5. Poor data control

6. Less data security

7. Integrity problems

8. Do not support transaction.

9. Conflicting requirements cannot be handled.

10. difficult to enforce standards.

1.2.3 Advantages of DBMS:-

1. Sharing of Data. 2. Reduction in redundancy (repetition)

3. Avoiding Inconsistency (data consistency) 4. Transaction support

5. Marinating Integrity 6. Enforcement of security

7. Balancing conflicting requirements 8. Enforcing standards


1. Sharing of Data:-

The data sharing is the feature which comes in the picture when multiple users access the same database
over the network. Many users may wish to access the same data at the same time. It is known as data
sharing. It is not possible in file processing system to share data over network

2. Reduction in redundancy (repetition):-

Repetition or duplication of data is called as data redundancy. In file processing system there is possibility
of storing repeated data at same time but in DBMS it is avoided to store same data to avoid the wastage of
disk space.

3. Avoiding Inconsistency:-

Inconsistency is the result of the data redundancy or duplication. We want to do various operation on data
such as insert, delete, update, and search but due to redundancy particular record is not affected properly is
called as data inconsistency.

But due to reduction in redundancy in dbms data consistency is maintained. Means correct data
manipulation operations can be done.

Data Consistency:-correctness of data is maintained means data manipulation operation can be executed
correctly.

4. Transaction support

Transaction is defined as the logical unit of the work or database work. A simple example is bank
operation .

Consider A account transfer Rs.1000/- to B account

This is called transaction.


In this there are two (Withdrawal and deposited) update operation at same time will be take place at
same time. Half transaction is not possible in DBMS. If it not done system either both operation would take
place or none of the operation will take place.

5. Maintaining Integrity:

Integrity means to ensure that the correct information is stored together in the database.

We would like to keep same constraints (restriction) on the data then it is called integrity constraints.

Example:- in bank there are certain rules for maintaining minimum balance in an account .

6. Enforcement of Security:-

Security is the major issue for data retrieval. To keep the sensitive data safe, the security should be
appropriate. Security is enforced by DBA (Database Administrator). DBA sets security constraints to the
users for the common operations like adding, deleting, retrieving, updating of the record.

7. Balancing conflicting requirements:-

This feature is used to balance the overall system requirements of the enterprise and the requirements of
the individual users.

8. Enforcing standards:

As the database are centralized the DBA has to ensure that the system follows all the possible applicable
standards. The standards can be departmental, installation, corporate, industry, national and international
standards.

1.2.4 Disadvantages of DBMS

1. Increased Cost: one of the disadvantages of dbms is Database systems require sophisticated hardware
and software and highly skilled personnel. The cost of maintaining the hardware, software, and personnel
required to operate and manage a database system can be substantial. Training, licensing, and regulation
compliance costs are often overlooked when database systems are implemented.
2. Complexity: Database systems interface with many different technologies and have a significant impact
on a company’s resources and culture. The changes introduced by the adoption of a database system must be
properly managed to ensure that they help advance the company’s objectives. Given the fact that database
systems hold crucial company data that are accessed from multiple sources, security issues must be assessed
constantly.
3. Currency Maintenance: To maximize the efficiency of the database system, you must keep your system
current. Therefore, you must perform frequent updates and apply the latest patches and security measures to all
components.
Because database technology advances rapidly, personnel training costs tend to be significant. Vendor
dependence. Given the heavy investment in technology and personnel training, companies might be reluctant to
change database vendors.
As a consequence, vendors are less likely to offer pricing point advantages to existing customers, and those
customers might be limited in their choice of database system components.

4. Performance:
5. Frequency Upgrade/Replacement Cycles: DBMS vendors frequently upgrade their products by adding
new functionality. Such new features often come bundled in new upgrade versions of the software. Some of
these versions require hardware upgrades. Not only do the upgrades themselves cost money, but it also
costs money to train database users and administrators to properly use and manage the new features.

6. Huge Size A database contains a large amount of data, especially for bigger organizations. This data may
even increase as more data is updated into the database. All of these leads to a large size of the database.

1.2.5 Difference between File Processing and DBMS

Here, are the difference between File System and DBMS

File System DBMS

A file system is a software that manages and organizes DBMS or Database Management System is a software
the files in a storage medium. It controls how data is application. It is used for accessing, creating, and
stored and retrieved. managing databases.

The file system provides the details of data DBMS gives an abstract view of data that hides the
representation and storage of data. details

Storing and retrieving of data can't be done efficiently DBMS is efficient to use as there are a wide variety of
in a file system. methods to store and retrieve data.

It does not offer data recovery processes. There is a backup recovery for data in DBMS.

The file system doesn't have a crash recovery DBMS provides a crash recovery mechanism
mechanism.
Protecting a file system is very difficult. DBMS offers good protection mechanism.

In a file management system, the redundancy of data is The redundancy of data is low in the DBMS system.
greater.

Data inconsistency is higher in the file system. Data inconsistency is low in a database management
system.

The file system offers lesser security. Database Management System offers high security.

File System allows you to stores the data as isolated Database Management System stores data as well as
data files and entities. defined constraints and interrelation.

Not provide support for complicated transactions. Easy to implement complicated transactions.

The centralization process is hard in File Management Centralization is easy to achieve in the DBMS system.
System.

It doesn't offer backup and recovery of data if it is lost. DBMS system provides backup and recovery of data
even if it is lost.

There is no efficient query processing in the file system. You can easily query data in a database using the SQL
language.

These system doesn't offer concurrency. DBMS system provides a concurrency facility.
1.3 Application of DBMS

1. Banking: - For customer information, account activities, payments, deposits, loans, etc.
2. Airlines/bus/railway/travels.:- For reservations and schedule information.
3. Universities: - For student information, course registrations, colleges and grades.
4. Credit card transactions
5. Tele Communication: - It helps to keep call records, monthly bills, maintaining balances, etc.
6. Finance: - For storing information about stock, sales, and purchases of financial instruments like
stocks and bonds.
7. Sales and marketing. : - Use for storing customer, product & sales information.
8. Online trading :-
9. Manufacturing Units. It is used for the management of supply chain and for tracking production of
items. Inventories status in warehouses.
10. Human Recourse developments. For information about employees, salaries, payroll, deduction,
generation of paychecks, etc.
11. Scientific Applications.
12. Government Departments.

1.4 Three Level Architecture of Database System

1.4.1 Data Abstraction:-

It can be defined as the process of hiding the complexity of data and representing the data which
needs to be shown to users. The complexity of database can be hiding from the user by different
level .The basic goal of database is to provide the user an efficient and convenient way to access the
data. And second is to provide an abstract view of the data. Abstract view hides the details of how
the data are stored and maintained. This means complicated details related to users are hides from
user.
1.4.2 DBMS Three Level Architecture Diagram (4 marks)

This architecture has three levels:


1. External level
2. Conceptual level
3. Internal level
1. External level (View Level)
It is also called view level. The reason this level is called “view” is because several users can view
their desired data from this level which is internally fetched from database with the help of
conceptual and internal level mapping. The user doesn’t need to know the database schema details
such as data structure, table definition etc. user is only concerned about data which is what
returned back to the view level after it has been fetched from database (present at the internal
level). External level is the “top level” of the Three Level DBMS Architecture.
2.Conceptual level (logical Level)
It is also called logical level. The whole design of the database such as relationship among data,
schema of data etc. are described in this level. Database constraints and security are also
implemented in this level of architecture. This level is maintained by DBA (database administrator).
3. Internal level (Physical Level)
This level is also known as physical level. This level describes how the data is actually stored in the
storage devices. This level is also responsible for allocating space to the data. This is the lowest level
of the architecture. In a database system is not multi-layered, then it becomes difficult to make any
changes in the database system. Database systems are designed in multi-layers.
1.5 Instance and Schema

1.5 Instance and Schema

• Instance:-Instances are the collection of information stored at a particular moment.


The instances can be changed by certain CRUD operations as like addition, deletion of data. It may
be noted that any search query will not make any kind of changes in the instances.
Example –
Let’s say a table teacher in our database whose name is School, suppose the table has 50 records so
the instance of the database has 50 records for now and tomorrow we are going to add another fifty
records so tomorrow the instance have total 100 records. This is called an instance.

• Schema: - Schema is the overall description of the database. The basic structure of how the data
will be stored in the database is called schema.
Schema is of two types: Logical Schema, Physical Schema and View Schema
1. Logical Schema – It describes the database designed at logical level.
2. Physical Schema – It describes the database designed at physical level.
3. View schema - Design of database at view level is called view schema. This generally describes
end user interaction with database systems.
Difference between Schema and Instance (4marks)
SCHEMA INSTANCE

It is the collection of information stored in


a database at a particular moment.
It is the overall description of the database.
Data in instances can be changed using
Schema is same for whole database. addition, deletion, updation.

Changes Frequently.

Does not change Frequently.


It is the set of Information stored at in the
Defines the basic structure of the database database at particular time.
i.e how the data will be stored
1.6 Data Independence

The ability to modify schema definition in one level without affecting schema definition in the next higher
level is called as data Independence.

A database system normally contains a lot of data in addition to users’ data. For example, it stores data
about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or update
a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change over time
to satisfy the requirements of the users. If the entire data is dependent, it would become a tedious and
highly complex job.

Metadata itself follows a layered architecture, so that when we change data at one layer, it does not affect
the data at another level. This data is independent but mapped to each other.

Logical Data Independence

Logical data is data about database, that is, it stores information about how data is managed inside. For
example, a table (relation) stored in the database and all its constraints, applied on that relation. Logical
data independence is a kind of mechanism, which liberalizes itself from actual data stored on the disk. If
we do some changes on table format, it should not change the data residing on the disk.

Physical Data Independence All the schemas are logical, and the actual data is stored in bit format on the
disk. Physical data independence is the power to change the physical data without impacting the schema or
logical data.
For example, in case we want to change or upgrade the storage system itself − suppose we want to
replace

hard-disks with SSD − it should not have any impact on the logical data or schemas.
3-tier Architecture
The design of a DBMS depends on its architecture. It can be centralized or decentralized or hierarchical. The
architecture of a DBMS can be seen as either single tier or multi-tier. An n-tier architecture divides the whole system
into related but independent n modules, which can be independently modified, altered, changed, or replaced. In 1-
tier architecture, the DBMS is the only entity where the user directly sits on the DBMS and uses it.
Any changes done here will directly be done on the DBMS itself. It does not provide handy tools for end-users. Database
designers and programmers normally prefer to use single-tier architecture.
If the architecture of DBMS is 2-tier, then it must have an application through which the DBMS can be
accessed. Programmers use 2-tier architecture where they access the DBMS by means of an application. Here the
application tier is entirely independent of the database in terms of operation, design, and programming.

3-tier Architecture
A 3-tier architecture separates its tiers from each other based on the complexity of the users and how they use the
data present in the database. It is the most widely used architecture to design a DBMS.s

• Database (Data) Tier − At this tier, the database resides along with its query processing languages. We also
have the relations that define the data and their constraints at this level.

• Application (Middle) Tier − At this tier reside the application server and the programs that access the
database. For a user, this application tier presents an abstracted view of the database. End-users are unaware
of any existence of the database beyond the application. At the other end, the database tier is not aware of
any other user beyond the application tier. Hence, the application layer sits in the middle and acts as a
mediator between the end-user and the database.

• User (Presentation) Tier − End-users operate on this tier and they know nothing about any existence of
the database beyond this layer. At this layer, multiple views of the database can be provided by the
application. All views are generated by applications that reside in the application tier.

• Multiple-tier database architecture is highly modifiable, as almost all its components are independent and
can be changed independently.
1.7 Overall Structure DBMS

Structure of DBMS:

DBMS (Database Management System) acts as an interface between the user and the database. The user
requests the DBMS to perform various operations such as insert, delete, update and retrieval on the
database.

The components of DBMS perform these requested operations on the database and provide necessary
data to the users.
Components of a DBMS or Overall Structure of DBMS -There are two major components of DBMS are
Storage manager and Query Processor

1. Storage manager:-it is referred as a program or module. Storage manager provides an


interface between the lower level data stored in the database and application programs. It
also acts as an interface between database and queries submitted to the system. The
storage manager compiles or translates the commands of data manipulation languages
into low level file system commands. And then accordingly they are executed.
There are four components:
1. Authorization and Integrity manager.
2. Transaction Manager.
3. File Manager.
4. Buffer Manager.
1. Authorization and Integrity manager:-
The major functions of this component is to check integrity constraints and check authority of
the user access to the data. Data integrity means correctness of the data to be stored in
database. Integrity constraints are the restriction on the data given by the users to
maintain integrity.
2. Transaction Manager:-
A Transaction is a collection of operations that performs a single logical function in a database
application. In transaction either both operation (Credit or Debit) should be done or not.
This is called as consistency. Transaction manager ensures that the database will be
consistent through the system gets fail.
3. File manager: - It manages the allocation of the space on disk. It allocates the required space to the
files which are stored on the storage disk.

4. Buffer manager: - buffer is the temporary memory which is used to transfer data from one device
to other. It manages the transfer of the data from one disk to the main memory. If the database is very large and
main memory is less. Such type of critical situations is handled by buffer manager.

Storage manager uses some data structures to represent as a part of the physical system implementations. These
are

Data File:- these are the files which stores the data itself. Data Dictionary:-this stores the data about data i.e.
metadata. This is about the structure of database in the schema. Indices (Index):- These are used for the fast
search of data in the database. Indexing means arranging the data in a particular order.
2. Query Processor:
It is second component of DBMS overall structure .It has following components

1. DDL (Data Definition Language) Interpreter

2. DML (Data Manipulation Language) complier

3. Query evaluation engine.

4. DML complier and Organizer

5. Complier and Linker

6. Application program object code.

1. DDL (Data Definition Language) Interpreter: DDL interpreter interprets or reads the DDL statements and
records the definitions of the file and add it’s to data dictionary.
2. DML (Data Manipulation Language) complier: - It translates DML statements into the low level instructions.
Low level instructions are understandable by query evaluation engine.
DML complier generates the evaluation plans which are then chosen by query evaluation engine.
3. Query evaluation engine: - Query evaluation engine executes the low level instructions generated by the DML
complier.

4. DML complier and Organizer: - This complies DML into lower level instructions and arranges or organizes the
output.
5. Complier and Linker: - It complies the instructions given by the user and the linker links them with the standard
library. Compilation is the process of converting programs written in high level languages to low level languages.
6. Application program object code:- Source code and object code refer to before and after versions of a
computer program that is compiled before it is ready to run in a computer.ie. Source code is the original program
written. Application program is viewed after execution of the source code. But when source code gets execute
first it gets convert into object code which is understandable by the computer system.
Database users:-
There are 4 types of Database Users

1. Naive Users.
These are unsophisticated users who interact with the system through the application programs. They may input
data through application programs or they may just view generated reports out of these application programs. An
interface for the naïve users is screens and reports etc.

2. Application Programmers.
Application programmers use programming tools to develop the programs. These applications are used by
Naïve users to interact with system

3. Sophisticated users.

These users interact with the system by making the requests in the form of query languages. These queries are
the submitted to query processor. Query processor then converts the DML statements into low level
instructions which are understandable by storage manager.

4. Specialized users.

These are the special users who are not traditional. They write some special application programs which are not
regular applications.

Ex. CAD, Knowledge based and experts systems.

These users also handles the system where data storage is complex. i. e. data can be in the form of graphics,
audio, video etc.

Functions of Database Administrator (DBA): (4marks)

DBA is a person who has central control over the data as well as the application program.

DBA is very responsible person as he/she has to do many important functions.

These are as follows

1. Schema Definition. 2. Storage structure and Access-method definition 3. Schema and physical-organization
modification.

4. Granting of authorization for data access. 5. Performance tuning. 6. Regular maintenance.


1.8 Data Models
It is used to represent the data. Data model can be defined as the collection of tools for describing data and
relationships among them, data semantics and consistency constraints. A mode is underlying or basic structure
of the database.

Following are the types of data models

1. Hierarchical Model:

A model in which data is organized into a tree like structure. This structure allows repeating information using
parent and child relationships. In this parent can have many children but child or children can have only one
parent. It is type of record based model. The data stored in the form of records. These records connected to one
other. Record is a collection of fields (column/data). Record is represented as row and fields as columns.

B C

D E F

Fig. Hierarchical Model


Advantages:-

a) Simple design

b)Database Integrity

c) Efficient

2. Network Model:-

The network model is a database model that uses an easy way of representing objects and their
relationships. This model is designed by Charles Bachman. This model allows every record to have multiple
parent and children records. This model forms web like or network like structure so it is called as network model.
Because of this network model allows modelling of many-to-many relationships while representing data.

Advantages:-

a) Design is simple.

b) Capability to handle various relationships

c) Easy to access.

Roll_no
Staff_Id Staff_Name S_Name

Staff Teaches Student

Fig. Network Model.


3. Relational Model:-

Relational model is based on the tables (Relation). Table is collections of rows and columns. Columns known as
attributes. Attributes (columns) are categories of the data which makes record or row. These tables are related
with each other by relations. RDBMS means Relational Database Management System. It is based on relational
model designed and developed by E.F.Codd. A table can be defined as a collection of interrelated records.
Properties of Relational Tables.

1. Values are Atomic (Values are not further divided)


2. Each Row is unique.
3. Column values are of the same kind/Type.
4. The sequence of columns is not important.
5. The sequence of rows is also not important.
6. Each column has unique name. Some columns (fields) can be designed as Keys.
Keys are used for searching specific values of a particular field. Relational Model is consist of relations i.e. tables.

Advantages:-
a) Simple b) user Friendly c) Flexible.

Fig. Relational Model.

Roll_No Stud_Name Address MobNo Fee

1 Latur 9456789562 20000


Kajal vasant
patil

2 Kiran halge Pune 9587565425 22000

3 Sakshi ghule Beed 9564879562 22000


A row in the table can be defined as a record and.

Column is defined as attribute of the table.

These attributes decides the categories of the information (data) which makes the record. Record is collection of
related information (data).

Domain can be defined as set of permitted values for a particular attribute.

Consider in fig 1.1 D1 as domain of Roll_no, D2 as domain of S_name, D3 as domain of Percentage and D4 as
domain of Rank.

Let’s consider any row of the fig.1.1 student table is consisting of the tuple (V1, V2, V3, and V4). Where V1 is
subset of D1 Values i.e. roll_no from set of roll numbers. V2 is from the subset of D2, V3 is from the subset of D3,
and V4 is from the subset of d4. Tuple is nothing but a Row or Record.

Advantages:-

a) Supports to SQL, b) Flexible.


4. Entity Relationship Model(ER Model):-
This will describe how one entity is related with another entity. ER models are used to represent the data in the
form of diagram called as ER diagram. These diagrams are can be then converted into actual table structures of
database.

ER model is a conceptual data model that views the real world as entities and relationships.

Entity :- It is a real world objects.

Ex.-persons, things, organizations etc. Persons like staff, students, employees, customers.etc

Things like book, accounts, products, train, airplane, bus

Organizations like college, universities, bank, shops, hotels, hospitals

Relationship: - it can be defined as an association among several entities.it exactly tells how one entity is related
to another entity.

Types of relationships are as:-

One to One,

One to Many,

Many to one and Many to Many


1.11 ER Diagrams

The pictorial representation of data using different conventions which state that how data are related to each
other is known as Entity relationship diagrams.

ER diagrams express the logical structure of database in graphical manner.

1.11.1 Components to draw ER diagrams:


1.11.2 Mapping Cardinality:-The degree to which one entity is related to other entity is called as cardinality of
the relation.

Types of relationships are as:-

1. One to One,

2. One to Many,

3. Many to one

4. Many to Many
1.10. 1 (B) Attributes these are nothing but properties of entities that describe the entities.

For ex. Students is an entity having attributes rollno, Sname, Address, Gender, Dob, Phno, year.

Book is entity having attributes bookid,bname, bprice, author etc.

Entity is nothing but set of attributes.

Domain is the set of permitted values for each attributes.

Ex.

Customer=(cust_code,cust_name,address,phno) Where customer is entity and cust_code,cust_name


,address , phno are attributes of customer entity.

Student=(rollno,sname,address,dob,phno,Age)

Book=(bid,bname,bprice)

Etc.

All attributes have values. For example, a student entity may have name, class, and age as attributes.

There exists a domain or range of values that can be assigned to attributes. For example, a student's name
cannot be a numeric value. It has to be alphabetic. A student's age cannot be negative, etc.

Types of Attributes:-

1. Simple attribute − Simple attributes are atomic values, which cannot be divided further.

For example, a student's phone number is an atomic value of 10 digits

2. Composite Attributes:-Composite attributes are made of more than one simple attribute. For example,
a student's complete name may have first_name and last_name. An attribute composed of many other
attribute is called as composite attribute. For example, Address attribute of student Entity type consists
of Street, City, State, and Country. In ER diagram, composite attribute is represented by an oval
comprising of ovals.

3. Derived attribute − Derived attributes are the attributes that do not exist in the physical
database, but their values are derived from other attributes present in the database. For example,
average_salary in a department should not be saved directly in the database, instead it can be
derived. For another example, age can be derived from data_of_birth.

4. Single-value attribute − Single-value attributes contain single value. For example −


Social_Security_Number.

5. Multi-value attribute − Multi-value attributes may contain more than one values. For example, a
person can have more than one phone number, email_address, etc.
6.Key Attribute:- The attribute which uniquely identifies each entity in the entity set is called key
attribute.For example, Roll_No will be unique for each student. In ER diagram, key attribute is
represented by an oval with underlying lines.
Chapter 2 Relational Data Model
2.1 Fundamentals of RDBMS
2.1.1 Introduction
Relational model is based on the tables (Relation). Table is collections of rows and columns.
Columns known as attributes. Attributes (columns) are categories of the data which makes record or
row. These tables are related with each other by relations. RDBMS means Relational Database
Management System. It is based on relational model designed and developed by E.F.Codd. A table can
be defined as a collection of interrelated records.
In relational model the data is stored in the different tables. These tables are interlinked to each
other with the help of common field in between them.
Definition:- A relational database is collectively combination of data structures, storage and retrieval
operations and integrity constraints.
In such database the data and relations between them are organized into tables.
Table is the collection of inter related records
2.1.2 Characteristics of Relational Database
-The tables of a relational database have some important characteristics:
-There is no logical significance to the order of the columns or rows.
-Each row contains either no value (a NULL column) or contains one and only one value for each
column.
-Each value for a given column is of the same type.

2.1.3 Advantages of Relational Model


1. Simple Model A Relational Database system is the most simple model, as it does not require
any complex structuring or querying processes. It doesn’t involve tedious architectural
processes like hierarchical database structuring or definition. As the structure is simple, it is
sufficient to be handled with simple SQL queries and does not require complex queries to be
designed.
2. Data Accuracy In the relational database system, there can be multiple tables related to
one another with the use of a primary key and foreign key concepts. This makes the data to be
non-repetitive. There is no chance for duplication of data. Hence the accuracy of data in the
relational database is more than any other database system.
3. Easy Access to Data Anyone who accesses the data can query any table in the relational
database. Using join queries and conditional statements one can combine all or any number of
related tables in order to fetch the required data. Resulting data can be modified based on the
values from any column, on any number of columns, which permits the user to effortlessly
recover the relevant data as the result. It allows one to pick on the desired columns to be
incorporated in the outcome so that only appropriate data will be displayed.
4. Data integrity It is a crucial characteristic of the Relational Database system. Sturdy Data
entries and legitimacy validations ensure that all the Data in the database confines within
suitable arrangements and the data necessary for creating the relationships are present. This
relational reliability amongst the tables in the database helps in avoiding the records from
being imperfect, isolated or unrelated.
5. Flexibility A Relational Database system by itself possesses qualities for leveling up,
expanding for bigger lengths, as it is endowed with a bendable structure to accommodate the
constantly shifting requirements. This facilitates the increasing incoming amount of data, as
well as the update and deletes wherever required. This model consents to the changes made
to a database configuration as well, which can be applied without difficulty devoid of crashing
the data or the other parts of the database.
6. Security As the data is divided amongst the tables of the relational database system, it is
possible to make a few tables to be tagged as confidential and others not. This segregation is
easily implemented with a relational database management system, unlike other databases.
When a data analyst tries to login with a username and password, the database can set
boundaries for their level of access, by providing admission only to the tables that they are
allowed to work on, depending on their access level.
2.1.4 Basic Concepts of Relational Model
1. Table: - collection of inter related data is called as table
It is combination of rows and columns. Where records are represented by rows
and attributes are represented by columns.
2. Tuple (Record):- Tuple is a single row of the table.
A tuple is an ordered set of attributes values.
3. Attribute (Field) it is a column of a table.
It is category of data. It also known as field.
4. Database:- it is collection of interrelated tables.
5. Domain:- set of permitted values for a particular attribute.

Properties of Relational Tables:


1. Data is presented as a collection of relations.
2. Each relation is depicted as a table.
3. Columns are attributes that belong to the entity modeled by the
4. Each row ("tuple") represents a single entity or an instance of that particular entity
5. Every table has a set of attributes that taken together as a "key" (technically, a "superkey")
uniquely identifies each entity (Ex. In the student table, “student ID” would uniquely identify
each student – no two students would have the same student ID).

Constraints: - restrictions on a column or attributes

To avoid repetition or duplication of data

To maintain integrity.

Integrity: - correctness of the data.


Definitions of Table, Tuple,Record, Attribute (field), database, domain

Consider the relation (table) Emp having attributes (columns) Emp_Id, E_name,Dept, BloodGrp, Ph_no
Emp
Emp_Id E_name Dept BloodGrp Ph_no
101 Naren Testing A+ 9564789562
102 Atharv Sales B+ 9421589554
103 Sarang Testing 9689878542

2.2 Concept of RDBMS


2.2.1 The 12 Rules (Codd’s Laws) for Fully Functional RDBMS
https://www.tutorialspoint.com/dbms/dbms_codds_rules.htm

Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up
with twelve rules of his own, which according to him, a database must obey in order to be regarded as a
true relational database. These rules can be applied on any database system that manages stored data
using only its relational capabilities. This is a foundation rule, which acts as a base for all the other rules.

Rule 1: Information Rule

The data stored in a database, may it be user data or metadata, must be a value of some table cell.
Everything in a database must be stored in a table format.

Rule 2: Guaranteed Access Rule

Every single data element (value) is guaranteed to be accessible logically with a combination of table-
name, primary-key (row value), and attribute-name (column value). No other means, such as pointers, can
be used to access data.

Rule 3: Systematic Treatment of NULL Values

The NULL values in a database must be given a systematic and uniform treatment. This is a very
important rule because a NULL can be interpreted as one the following − data is missing, data is not
known, or data is not applicable.

Rule 4: Active Online Catalog

The structure description of the entire database must be stored in an online catalog, known as data
dictionary, which can be accessed by authorized users. Users can use the same query language to access
the catalog which they use to access the database itself.
Rule 5: Comprehensive Data Sub-Language Rule

A database can only be accessed using a language having linear syntax that supports data definition, data
manipulation, and transaction management operations. This language can be used directly or by means of
some application. If the database allows access to data without any help of this language, then it is
considered as a violation. SQL is a commercial database language used
by RDBMS

Rule 6: View Updating Rule

All the views of a database, which can theoretically be updated, must also be updatable by the system.
View should support operations like data manipulation.

Rule 7: High-Level Insert, Update, and Delete Rule

A database must support high-level insertion, updation, and deletion. This must not be limited to a single
row, that is, it must also support union, intersection and minus operations to yield sets of data records.

Rule 8: Physical Data Independence

The data stored in a database must be independent of the applications that access the database. Any
change in the physical structure of a database must not have any impact on how the data is being
accessed by external applications.

Rule 9: Logical Data Independence

The logical data in a database must be independent of its user’s view (application). Any change in logical
data must not affect the applications using it. For example, if two tables are merged or one is split into two
different tables, there should be no impact or change on the user application. This is one of the most
difficult rule to apply.

Rule 10: Integrity Independence

A database must be independent of the application that uses it. All its integrity constraints can be
independently modified without the need of any change in the application. This rule makes a database
independent of the front-end application and its interface.

Rule 11: Distribution Independence

The end-user must not be able to see that the data is distributed over various locations. Users should
always get the impression that the data is located at one site only. This rule has been regarded as the
foundation of distributed database systems.

Rule 12: Non-Subversion Rule

If a system has an interface that provides access to low-level records, then the interface must not be
able to subvert the system and bypass security and integrity constraints.
2.2.2 Key Concepts:-
Tables required for storing the data is huge, and the different tables are related to each other as well.
Keys :- These are defined Key is referred to the attribute which is important. Means a value of attributes
allows to easily identify any row of data in a table.

Key attribute:-No two tuples (records) in the table (relation) are allowed to have exactly the same values
for the attributes.

Types of keys
1. Primary key
2. Super key
3. Candidate key
4 Foreign Key
5. Composite Key
6. Alternate Keys.
https://www.studytonight.com/dbms/databasekey.php#:~:text=Keys%20are%20very%20important%20part
,may%20act%20as%20a%20key.

1. Primary Key:
It can be defined as a unique attribute (column) of a table (relation) which allows storing only unique values
and also these values are never null.
The two requirements for a primary key are:
1. Every value should be unique in the column of primary key
2. Column values should not be null or empty

2. Super Key:-
It is set of one or more attributes (columns) that taken collectively allows us to identify a tuple (record) in
the relation (table).
Ex. In Emp table Emp_Id is super key or combination of (Emp_name and Emp_dept)
3. Candidate key:-
It can be single attribute or the set of attributes.
The super keys for which no proper subset is a super key such minimal super keys are called as candidate
key.
A candidate key can never be NULL or empty. And its value should be unique.
There can be more than one candidate keys for a table.
A candidate key can be a combination of more than one columns (attributes).
4. Composite Key
Key that consists of two or more attributes that uniquely identify any record in a table is called Composite
key. But the attributes which together form the Composite key are not a key independently or individually
5. Alternative key The candidate key which are not selected as primary key are known as secondary keys
or alternative keys.
6. Foreign Key:-
Let’s consider two relations (tables) r1 and r2. If r1 includes primary key of relation (table) r2 then this
attribute is called as Foreign Key from r1 referencing r2. Or
A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or collection of
fields) in one table that refers to the PRIMARY KEY in another table.
Consider two schemas loan and customer
Customer_schema= (Cust_id, Loan_id, Name, Address)
Loan_schema= (Loan_id, Branch_name, Amount)
In this customer schema is referencing schema and loan schema is called as referenced relation.
The attribute (column) loan_id is primary key of loan schema which is used in customer schema. An attribute
loan_id is called as foreign key in customer schema.
Table –Customer (r1)(child table)
Cust_id(primary key) Loan_id(foreign key) Name address
1111 11 Ram latur

Table – Loan (r2)(Parent table)

Loan_id(primary key) Branch_name Amount


11 latur 12000

On delete Cascade clause:- A foreign key with cascade delete means that if a record in the parent table is
deleted, then the corresponding records in the child table will automatically be deleted.
2.3 Normalization:-

It can be defined as process of decomposition of database tables to avoid the data redundancy.
Database normalization is a database design technique by which relational database tables are structured
or designed in such a way that to make them user and even system friendly.
Redundancy in relation may cause insertion, deletion and updation anomalies. So, it helps to minimize the
redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables.
Data redundancy unnecessarily increases the size of the database as the same data is repeated in many
places. Inconsistency problems also arise during insert, delete and update operations.
Functional Dependency:-
It can be defined as a column Y of the relation table R is said to be functionally dependent upon column
X of R if and only if each value of X in R is associated with exactly one value of Y at any given time.
The functional dependency is a relationship that exists between two attributes. It typically exists between the
primary key and non-key attribute within a table.
R.x R.y
The left side of FD is known as a determinant, the right side of the production is known as a dependent.
It can be read as column X functionally determines or identifies column Y in relational table R.
Functional Dependency is a constraint between two sets of attributes in a relation from a database. A
functional dependency is denoted by arrow (→). If an attributed A functionally determines B, then it is
written as A → B.
2.3.1 Types of Normal forms

1. First Norm (1NF.):- Having unique values, no repeating Values.


2. Second Normal Form (2NF.):- having unique values, no repeating values, no partial dependency.
3. Third Normal Form (3NF.):- same as 2NF and having Transitive dependency.
4. BCNF (Boyee-Codd Normal Form).

2.3.2 Purpose of Normalization:-


If a database design is not perfect, it may contain anomalies, which are like a bad dream for any database
administrator. Managing a database with anomalies is next to impossible.
2.3.3 Anomalies stand for irregularity
a) Update anomalies − If data items are scattered and are not linked to each other properly, then it could
lead to strange situations. For example, when we try to update one data item having its copies scattered
over several places, a few instances get updated properly while a few others are left with old values. Such
instances leave the database in an inconsistent state.

b) Deletion anomalies − we tried to delete a record, but parts of it was left undeleted because of
unawareness, the data is also saved somewhere else.
c) Insert anomalies − we tried to insert data in a record that does not exist at all.

Normalization is a method to remove all these anomalies and bring the database to a consistent state.
Consider following table Student_Activity
Rollno Sname Div Activity_code Activity Fees
1 Yogesh A A1 Drawing 200
2 Prathmesh A A2 Swimming 350
3 Durva B A1 Drawing 200
4 Atharva B A2 Swimming 350
5 Prachi C A3 Craft 100
Student
Rollno Sname Div
1 Yogesh A
2 Prathmesh A
3 Durva B
4 Atharva B

Activity
Activity_code Activity Fees
A1 Drawing 200
A2 Swimming 350
A1 Drawing 200
A2 Swimming 350
A3 Craft 100

Stu_activity
Rollno Activity Code
1 A1
2 A2
3 A1
4 A2
5 A3

Student and Activity table are called as master tables and Stu_activity is called as transaction table.
2.4 First Normal Form (1NF)
-A relation will be 1NF if it contains an atomic value.
-It states that an attribute of a table cannot hold multiple values. It must hold only single-valued
attribute.
-First normal form disallows the multi-valued attribute, composite attribute, and their combinations.
Example: Course_Details

Course_Id Course_name Languages

1 Programming C

2 Programming VB

3 Scripting PHP

4 Scripting HTML
2.5. Second Normal Form (2NF)

-In the 2NF, relational must be in 1NF.


- In the second normal form, all non-key attributes are fully functional dependent on the primary key
Example: Let's assume, a school can store the data of teachers and the subjects they teach. In a school, a
teacher can teach more than one subject.

TEACHER table

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30
47 English 35

83 Math 38

83 Computer 38

In the given table, non-prime attribute TEACHER_AGE is dependent on TEACHER_ID which is a proper
subset of a candidate key. That's why it violates the rule for 2NF.
To convert the given table into 2NF, we decompose it into two tables:

TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30

47 35

83 38
TEACHER_SUBJECT table:

TEACHER_ID SUBJECT

25 Chemistry

25 Biology

47 English

83 Math

83 Computer
2.6.Third Normal Form (3NF)
-A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
- 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
-If there is no transitive dependency for non-prime attributes, then the relation must be in third normal
form.
A relation is in third normal form if it holds at least one of the following conditions for every non-trivial
function dependency X → Y.
X is a super key.
Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example: EMPLOYEE_DETAIL table

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on

Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except EMP_ID are non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on EMP_ID. The non-
prime attributes (EMP_STATE, EMP_CITY) transitively dependent on super key(EMP_ID). It violates the
rule of third normal form.
That's why we need to move the EMP_CITY and EMP_STATE to the new <EMPLOYEE_ZIP> table, with
EMP_ZIP as a Primary key.
Employee Table:-

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida
2.7 Introduction To Structured Querry language
-SQL stands for Structural Query Language.
-SQL is used to communicate with a database.it is the standard language for relational database
management systems. SQL statements are used to perform different operations on database like
retrieval, insertion, updatation and deletion called as data manipulation of data.
-SQL (Structured Query Language) is used to perform operations on the records stored in the database
such as updating records, deleting records, creating and modifying tables, views, etc.
-SQL is just a query language; it is not a database. To perform SQL queries, you need to install any
database for example, Oracle, MySQL, MongoDB, PostGre SQL, SQL Server, DB2, etc.
What is SQL?
SQL stands for Structured Query Language.
o It is designed for managing data in a relational database management system (RDBMS).

o It is pronounced as S-Q-L or sometime See-Qwell.

o SQL is a database language, it is used for database creation, deletion, fetching rows, and modifying
rows, etc.

o SQL is based on relational algebra and tuple relational calculus.

All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL Server use SQL as standard
database language.

Why SQL is required


- With SQL, we can query our database in several ways, using English-like statements.
- With SQL, a user can access data from a relational database management system.
- It allows the user to describe the data.
- It allows the user to define the data in the database and manipulate it when needed.
- It allows the user to create and drop database and table.
- It allows the user to create a view, stored procedure, function in a database.
- It allows the user to set permission on tables, procedures, and views.

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.
SQL process:

- When an SQL command is executing for any RDBMS, then the system figure out the best way to carry
out the request and the SQL engine determines that how to interpret the task.
- In the process, various components are included. These components can be optimization Engine, Query
engine, Query dispatcher, classic, etc.
- All the non-SQL queries are handled by the classic query engine, but SQL query engine won't handle
logical files.

2.7.1 Characteristics of SQL


- SQL is easy to learn.
- SQL is used to access data from relational database management systems.
- SQL can execute queries against the database.
- SQL is used to describe the data.
- SQL is used to define the data in the database and manipulate it when needed.
- SQL is used to create and drop the database and table.
- SQL is used to create a view, stored procedure, function in a database.
- SQL allows users to set permissions on tables, procedures, and views.
2.7.2 Advantages of SQL
There are the following advantages of SQL:
1. High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records from a
database.
2. No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a substantial
amount of code to manage the database system.
3. Well defined standards
Long established are used by the SQL databases that are being used by ISO and ANSI.
4. Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
5. Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive answers to
the complex questions in seconds.
6. Multiple data view
Using the SQL language, the users can make different views of the database structure.
2.8 SQL Data Types
Data types are used to represent the nature of the data that can be stored in the database table.
For example, in a particular column of a table, if we want to store a string type of data then we will have
to declare a string data type of this column.
SQL Data type is used to define the values that a column can contain.
Every column is required to have a name and data type in the database table.
Data types mainly classified into three categories for every database.
-String Data types.
-Numeric Data types.
-Date and time Data types
2.9 Components of SQL:
SQL statements are categorized as DDL, DML, DCL and TCL, DQL
1. Data Definition Language (DDL) 2.
Data Manipulation Language (DML).
3. Data Control Language (DCL)
4. Transaction Control Language (TCL)
5. Data Query Language (DQL).
Each sql statement end with (;) semicolon.
2.9.1. Data Definition Language (DDL):-
This language allows the users to define the basic structure of database or tables. DDL is also used to
specify the structure of each table, set of associated values with each attribute, integrity constraints etc. for
all the tables.
There are following types of DDL statements.
a)Create, b) Alter, c) Drop d) Rename, e) TRUNCATE f) Describe g) comment.

a) Create:-this statements is used to create database and its objects like table, view, store procedure,
trigger, sequences, function, index etc. in a database.
There are two CREATE statements available in SQL:
1. CREATE DATABASE.
2. CREATE TABLE.
1. CREATE DATABASE:-
The CREATE DATABASE statement is used to create a new database in SQL.
Syntax:
CREATE DATABASE database_name;
Ex:- create database college;
After executing this command college database is created.
2. CREATE TABLE:-
The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of rows and
columns. So while creating tables we have to provide all the information to SQL about the names of the
columns, type of data to be stored in columns, size of the data etc.
While giving names to table and columns there are following rules.
1. A name can be of maximum up to 30 characters.
2. A-Z and a-z and numbers 0-9 are allowed.
3. The name should begin with an alphabet.
4. The special symbol ‘_’(underscore)only is allowed
5. Reserve words are not allowed to give name to table and column.

syntax:-
Create table tablename (columnname1 datatype (size), columnname2 datatype (size), columnname3
datatype (size), columnname4 datatype (size),…., columnname n datatype (size)); Where tablename:
name of the table. columnname1 name of the first column.
datatype: Type of data we want to store in the particular column.
For example,int for integer data.
size: Size of the data we can store in a particular column. For example if for a column we specify the
data_type as int and size as 10 then this column can store an integer number of maximum 10 digits.
Ex.
Create table student (rollno number (4) primary key, stud_name varchar (50), phone_no number (10)); Table
name:-student
Rollno Stud_name Phone_no

b) Alter: - this command is used to alter or modify the basic structure of database objects like table, view,
procedure, trigger, sequences, index etc. With alter table statement adding and deleting of the column is
possible.
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and
drop various constraints on the existing table.
1. Delete column:-
Alter table tablename delete (columnname);
OR
Alter table tablename drop column columnname;
Ex: Alter table student delete (phone_no);
Alter table student drop column phone_no;
Desc student;
Rollno Stud_name

2. Add column :
Alter table tablename add (columnname datatype (size));
Ex: Alter table student add (city varchar (10));
Rollno Stud_name city

3. modify column:-
If we want to change datatype or size of column.
Alter table tablename modify columnname new datatype (new size);
Ex: Alter table student modify city varchar (20);
4. Rename column:-if we want to change column name Syntax:-
Alter table tablename rename column old columnname to new columnname; Ex:-
alter table student rename city to address
Rollno Stud_name address

C) Drop: - it is used to delete objects from the database.


DROP is used to delete a whole database or just a table. The DROP statement destroys the objects like an
existing database, table, index, or view. A DROP statement in SQL removes a component from a relational
database management system (RDBMS).
Syntax:-
DROP object object_name;
Examples:
DROP TABLE table_name; table_name: Name of
the table to be deleted.

DROP DATABASE database_name; database_name: Name of


the database to be deleted.
If we want to drop table from database
Ex. Drop table student;
After executing this command table and data present in table also deleted from database.
d) Rename table:- It is used to rename an object existing in the database.
If we want to change name of table then we use rename command.
Syntax:-rename old tablename to new tablename;
Ex:- rename student to student_details;

e) TRUNCATE:-is used to remove all records from a table, including all spaces allocated for the records
are removed.
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark the extents
of a table for deallocation (empty for reuse). The result of this operation quickly removes all data
from a table. Syntax:-
TRUNCATE TABLE table_name; table_name: Name of
the table to be truncated.
f) DESCRIBE :- DESCRIBE is used to describe something. Since in database we have tables, that’s why

Syntax:
DESCRIBE tablename;
OR
DESC tablename;
Ex:- desc student
Name Null Type
Rollno Notnull number (4)
Stud_name VARCHAR(50)
Phone_no NUMBER(10)

g) Creating a User:-
we use DESCRIBE or DESC(both are same) command to describe the structure of a table.
It is used to create the user. We need to specify user name and identified by. User can be identified
by externallyor globally. Password expire is another clause used with creating user.
Syntax:
Create user username identified by password externally;

Ex:- create user ajay identified by admin externally;

Data Integrity Constraints:-


o Integrity constraints are a set of rules. It is used to maintain the quality of information.

o Integrity constraints ensure that the data insertion, updating, and other processes have to be performed in such a way
that data integrity is not affected.

o Thus, integrity constraint is used to guard against accidental damage to the database.

Integrity constraint is a mechanism to prevent invalid data entry into table to maintain the data
consistency.
Data integrity is related to completeness and correctness of the data in a database.
So to maintain data consistency constraints (restrictions) are used to enforce limits to range of data.
Constraints are the rules enforced on the data columns of a table. These 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 database.
Constraints could be either on a column level or a table level. The column level constraints are applied only to one
column, whereas the table level constraints are applied to the whole table.
Constraints can be specified when a table is created with the CREATE TABLE statement or you can use the ALTER
TABLE statement to create constraints even after the table is created.
Types of Integrity Constraint:-
Following are the types of integrity constraints 1.
Domain Integrity constraint.
2. Entity Integrity constraint.
3. Referential Integrity constraint.
4. Key constraint.

1. Domain Integrity constraints:-


o Domain constraints can be defined as the definition of a valid set of values for an attribute. o The data type of
domain includes string, character, integer, time, date, currency, etc. The value of the attribute must be

available in the corresponding domain.

2. Entity integrity constraints (Primary Key)

o The entity integrity constraint states that primary key value can't be null.

o This is because the primary key value is used to identify individual rows in relation and if the primary key has a null
value, then we can't identify those rows.

o A table can contain a null value other than the primary key field.

3. Referential Integrity Constraints (Foreign Key)


o A referential integrity constraint is specified between two tables.

o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2, then every value
of

the Foreign Key in Table 1 must be null or be available in Table 2.

4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.

o An entity set can have multiple keys, but out of which one key will be the primary key. A primary key can contain a
unique and null value in the relational table.

Business Rule Constraints:-

1. NOT NULL:
NOT NULL constraint makes sure that a column does not hold NULL value. When we don’t provide value for
a particular column while inserting a record into a table, it takes NULL value by default. By specifying NULL
constraint, we can be sure that a particular column(s) cannot have NULL values.

Example:

CREATE TABLE STUDENT (


ROLL_NO INT Primary Key,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (235));
ROLL_NO STU_NAME STU_AGE STU_ADDRESS

2. UNIQUE:

UNIQUE Constraint enforces a column or set of columns to have unique values. If a column has a unique
constraint, it means that particular column cannot have duplicate values in a table.

CREATE TABLE STUDENT(


ROLL_NO INT PRIMARY KEY,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
);
3. DEFAULT:

The DEFAULT constraint provides a default value to a column when there is no value provided while
inserting a record into a table.

CREATE TABLE STUDENT(


ROLL_NO INT PRIMARY KEY,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35));
4. CHECK:

This constraint is used for specifying range of values for a particular column of a table. When this constraint
is being set on a column, it ensures that the specified column must have the value falling in the specified
range.

CREATE TABLE STUDENT(


ROLL_NO INT PRIMARY KEY CHECK(ROLL_NO >1000) ,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35));
In the above example we have set the check constraint on ROLL_NO column of STUDENT table. Now, the
ROLL_NO field must have the value greater than 1000.

Key constraints:
1. PRIMARY KEY:

Primary key uniquely identifies each record in a table. It must have unique values and cannot contain nulls. In
the below example the ROLL_NO field is marked as primary key, that means the ROLL_NO field cannot
have duplicate and null values.

Alter table tablename add constraint constraintname primary key (column-name);


Ex:- alter table STUDENT add constraint STUDENT_pk primary key ("ROLLNO") ;

CREATE TABLE STUDENT(


ROLL_NO INT PRIMARY KEY,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
);
2. FOREIGN KEY:

Foreign keys are the columns of a table that points to the primary key of another table. They act as a
crossreference between tables.
It is also called as Referential Integrity Constraint.in this constraint one field is common in between two
tables.
It represent relationship between tables. There is parent child relationship between two tables having
common column.
Ex. Create table student(stud_id number(5),name varchar(25),course_code references
course_details(course_code));
Here course_code column which primary key in course_details table is used as foreign key. Table1:-
Course_details(parent Table)

course_code(Primary Key) Course_name

Tbale2:- Student(Child table)


stud_id name course_code(Foreign
Key)

On delete Cascade clause:- A foreign key with cascade delete means that if a record in the parent table is
deleted, then the corresponding records in the child table will automatically be deleted.
Domain constraints:

Each table has certain set of columns and each column allows a same type of data, based on its data type.
The column does not accept values of any other data type.
Domain constraints are user defined data type and we can define them like this:
Create domain or alter domain can be used to assign this constraints.
Syntax: - Create domain domainname as datatype;
Ex:- 1.Create domain itemcode as char (2) not null;
2.Create table itemlist(id int (4),itemcd itemcode);
The example create itemcode as a datatype and then used in create table command as a datatype of
itemcd attribute.
//////////////////write answer//////////////////
Q.1.Consider the following schema
Emp(emp_no as primary key, e_name,dept_no ,dept_name,job_id,salary)
Write a queries for-
1. Creating above table.
Ans:- create table Emp(emp_no int(4) primary key,e_name varchar(25), dept_no
int (2),dept_name varchar (25),job_id varchar(20), salary number(7,2));
2 .add emp_phone column to above table
Ans:- Alter table Emp add column emp_phone int(10);
3. Modify size of column dept_name to 30.
Ans:- Alter table Emp modify dept_name varchar(30);
4. Rename column salary to emp_sal.
Ans:-alter table Emp rename column salary to emp_sal;

Q.2. Consider the following schema


Employee (empno, ename, job, mgr, hiredate, sal, comm, deptno)
Write queries for –
1. Creating above table.
Ans:-Create table Employee (empno int (4), ename varchar (25),
job varchar (20), mgr int(4),hiredate date,sal number(10), comm
number(10),deptno int(2));
2. Modify column sal to salary.
Ans:- Alter table Employee modify sal to salary;
3. Delete column comm from employee.
Ans:- Alter table Employee delete (comm);
4. Drop table
Ans:-drop table Employee;
Q.3. consider the following schema Write queries for creating following tables.
a)Emp1(empno as primary key,empname,salary,phono)
Ans:- Create table Emp1(empno int primary key,empname varchar(25), salary
number (10,2)phono int(10);)
b)Dept(deptno as primary key, deptname,location, empno as foreign key)
Ans:- create table Dept(deptno int primary key, deptname varchar(25), location
varchar(20), empno int references Emp1(empno),);
Q.4. create table for stud using attributes Rollno, studname, percentage apply primary key for Rollno and
check constraint on percentage should not greater than 100.
Ans: - create table stud (Rollno int (4), studname varchar (20), percentage number (5,2) check (percentage<=100));
Q.5 change above stud table by adding column city.
Ans: - alter table stud add column city varchar (20); Q.6
increase the size by 10 of studname column.
Ans: - alter table stud modify studename varchar (30);

Q.7. consider schema passenger_details (passenger_name varchar2 (30), train_details varchar2 (30),
travelling_date (date), birthdate (date)) Write query for creating this table.
Ans: - create table passenger_details (passenger_name varchar2 (30), train_details varchar2 (30), travelling_date
date, birthdate date);
Q8. Add column ticket_cost (int) to above column.
Ans: - Alter table passenger_details add column ticket_cost int (4);
Q.9 create a table emp2 with following schema:-
Emp2 (emp_no, e_name, dept_no, dept_name, job_id, salary, hiredate).
Ans:- create table Emp2(emp_no int(4),e_name varchar(25),dept_no
int(4),dept_name varchar(25),job_id number(10),salary number(10,2),hiredate
date);

After executing this command Emp2 table will be created as Table name:-Emp2
emp_no e_name dept_no dept_name job_id salary hiredate q.10- insert 5 records
in each table which is created.
2. Data Manipulation Languages (DML):-
Following are DML statements used to do various data manipulation operations such as adding new
record(insert),updating record(modification),deleting record, searching(retrieving data) .
1. Insert:-
The INSERT statement is a SQL query. After creating table successfully now records can be entered. Insert is used to
insert data into the row of a table.
Syntax:- a)
INSERT INTO TABLENAME(col1, col2, col3,...., col N) VALUES (‘value1’, ‘value2’, ‘value3’,....,‘valueN’);

OR

b) INSERT INTO TABLE_NAME VALUES (‘value1’,’value2’, ‘value3’ , … ,‘valueN’);

When we use numeric values for inserting data do not use ‘ ‘ symbol

Ex:-1- insert into emp2 values (111,’prathmesh patil’, 10,’sales’, 111, 25000,’28-09-2014’);
2- insert into emp2 values(112,’Shreyas’,10,’sales’,112,30000,’18-09-2013’);

Either all rows will be updated or modified or selected rows can be modified using where clause.
Syntax:-
a) UPDATE table_name SET column_name1= ‘value1’,...,column_nameN =’ valueN’;
b) UPDATE table_name SET column_name1= ‘value1’,...column_nameN = ‘valueN’ where condition;
After executing this command dept_no of all employees wii be updated to 30
emp_no e_name dept_no dept_name job_id salary Hiredate
111 Prathmesh patil 30 Sales 111 25000 28-09-2014

112 Shreyas 30 Sales 112 30000 18-09-2013

3. Delete:-
Ex:-1-update Emp2 set dept_no=20 where emp_no=112;
After executing this command dept_no of emp_no 112 is updated to 20
emp_no e_name dept_no dept_name job_id salary Hiredate
111 Prathmesh patil 10 Sales 111 25000 28-09-2014

112 Shreyas 20 Sales 112 30000 18-09-2013

111 Prathmesh patil 30 Sales 111 25000 28-09-2014

2.delete from emp2;


emp_no e_name dept_no dept_name job_id salary Hiredate

After executing this command whole record present in a table will be deleted.
2- update Emp2 set dept_no=30;
It is used to remove one or more row from a table. Syntax:-

1. DELETE FROM table-name;

2. DELETE FROM table-name WHERE condition;


Ex:- 1. delete from emp2 where emp_no=112;
After executing this command only record of empno 112 will be deleted.
emp_no e_name dept_no dept_name job_id salary Hiredate
Create table Employee (empno int (4), ename varchar (25), job varchar (20), mgr int(4),hiredate date,sal
number(10),comm number(10),deptno int(2));
After executing this command following tbale will be created:
Table:-Employee
empno ename job mgr hiredate sal comm deptno
Do following operations on Employee table
1. Insert into table Employee values (7839,’king’,’presedent’, ’ ‘, ’11/10/1981’, 5000, ‘ ‘ ,10);
empno ename job mgr hiredate sal comm Deptno
7839 king president 11/10/1981 5000 10
7698 Blake Manager 7839 07/05/1981 2850 30
7782 Clark Manager 7839 06/09/1981 2450 10
7566 Jones Manager 7839 04/02/1981 2975 20
7788 Scott Analyst 7566 12/09/1982 3000 20
7902 Ford Analyst 7566 11/03/1981 3000 20
7369 Smith Clerk 7902 11/04/1981 800 20
7499 Allen salesman 7698 02/02/1981 1600 300 30
7521 Ward salesman 7698 02/04/1981 1250 500 30
7654 Martin salesman 7698 09/03/1981 1250 1400 30
7844 Turner salesman 7698 11/08/1981 1500 0 30
7876 Adams clerk 7788 01/12/1983 1100 20
7900 James clerk 7698 11/03/1981 950 30
7934 Miller clerk 7782 01/10/1981 1300 10

3. DCL(Data Control Language)


These statements are used to create privileges to permit users to access and do manipulation
operations on database.
A DCL statement manages the authority to access data that users have on database objects.
DCL commands are used to grant and take back authority from any database user. Here are some
commands that come under DCL:
1. Grant
2. Revoke

a. Grant: - Whenever we want to work with database then we must have some privileges to work on it.
If we don’t have authority to database then we can’t perform any operation in the database like insert, update,
delete.
It is used to give user access privileges to a database. Syntax:-

GRANT privileges ON object-name TO username;

Here privileges means insert, update, delete, and search/select.

Ex; -1. Grant insert, select on emp to amit;

Here user amit has only permission to insert new record and retrieve the data.other data manipulation operations
such as update, delete are not permitted to user amit.

2. Grant update, select on emp to ajay;

Here user ajay has only permission to update record and retrieve the data.other data manipulation operations such
as insert, delete are not permitted to user amit.

b. Revoke:-
It is used to take back permissions from the user.
Syntax:-
Revoke privileges on object-name from user;
Ex:- revoke insert, select on emp from amit;
Here the privileges select and update will be revoked or take back on emp table from user amit.
4. Transaction Control Language (TCL)

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating tables or dropping
them.

Here are some commands that come under TCL:

o COMMIT
o
ROLLBAC
K o
SAVEPOI
NT

a. Commit: Commit command is used to save all the transactions to the database. This
command is used to save the data permanently.
Whenever we perform any of the DDL command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored
permanently. So in order to be at the safer side COMMIT command is used.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS

2. WHERE AGE = 25;

3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database. This command is
used to get the data or restore the data to the last savepoint or last commited state. If due to some reasons the data inserted, deleted
or updated is not correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to the last commited state.

Syntax:

1. ROLLBACK;

Example:
1. DELETE FROM CUSTOMERS

2. WHERE AGE = 25;

3. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.
This
command is used to save the data at a particular point tempoararily, so that whenever needed can be rollback to that
particular point.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
1. INSERT into STUDENT
2. VALUES ('Jack', 95);
3.
4. Commit;
5.
6. UPDATE NAME
7. SET NAME= ‘Rossie’
8. WHERE marks= 70;
9.
10. SAVEPOINT A;
11.
12. INSERT INTO STUDENT
13. VALUES (‘Zack’, 76);
14.
15. Savepoint B;
16.
17. INSERT INTO STUDENT
18. VALUES (‘Bruno’, 85);
19.
20. Savepoint C;
21.
22. SELECT *
23. FROM STUDENT;
5. Data Query Language (DQL)

DQL is used to fetch the data from the database. It is used to retrieve the data from database.

Select is the most commonly used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetch data from a
database. We can fetch either the entire table or according to some specified rules. The data returned is stored in a result table. This
result table is also called result-set.

It uses only one command:

o SELECT

Select command is used in various forms as per user need how to retrieve data.
a) Select * from table-name;
b) Select column-name1, column-name2,….., column-name n from table-name;
c) Select * from table-name where condition; Ex:-1.select * from student:
All records present in student table will be displayed on screen.
2. Select rollno, name from student;
Only data present in rollno and name column will be displayed.
3. Select * from student where rollno=2; Only rollno 2 record
will be displayed.

Add constraint on column after table creation:


Syntax:
Alter table tablename add constraint constraintname primary key (column-name);
Ex:- alter table STUDENT add constraint STUDENT_pk primary key ("ROLLNO") ;
1. Where clause
It is used to specify condition in select statement while feteching records from the database.
The records satisfying the condition biven by where clause are retrieved Syntax:
Select *from table name where condition;
Select column1,column2,….,column n from table name where condition;
2. Distinct Clause
This clause is used to avoid selection of duplicate rows.
Syntax:
Select distinct (columnname) from tablename;
Ex;- select distinct(job)from emp;
It will display only distinct or avoid repeated column values.
Operator in SQL
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform
operation(s), such as comparisons and arithmetic operations. These Operators are used to specify conditions
in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
Types.
To operate on the values or numbers operators are used. Operators
are symbols used to do certain operations.

• Arithmetic operators
• Comparison operators
• Logical operators
• Bitwise Operators. Compound Operators Set Operators.

• Range Searching Operators.


• Patterns matching operators.
SQL Arithmetic Operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. a + b will give 30

- (Subtraction) Subtracts right hand operand from left hand operand. a - b will give -10

* (Multiplication) Multiplies values on either side of the operator. a * b will give 200

/ (Division) Divides left hand operand by right hand operand. b / a will give 2
% (Modulus) Divides left hand operand by right hand operand and returns remainder. b % a will give 0

SQL Comparison Operators


Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Comparison operators are used to compare the values.

Operator Description Example

= Checks if the values of two operands are equal or not, if yes then condition becomes true. (a = b) is
not true.

!= Checks if the values of two operands are equal or not, if values are not equal then condition (a != b)
becomes true. is true.

<> Checks if the values of two operands are equal or not, if values are not equal then condition (a <> b)
becomes true. is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then (a > b) is
condition becomes true. not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition (a < b) is
becomes true. true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes (a >= b)
then condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes (a <= b)
then condition becomes true. is true.

!< Checks if the value of left operand is not less than the value of right operand, if yes then (a !< b)
condition becomes true. is false.

!> Checks if the value of left operand is not greater than the value of right operand, if yes then (a !> b)
condition becomes true. is true.
SQL Logical Operators
Here is a list of all the logical operators available in SQL.
Logical operators mainly help in evaluating the expression that depends upon specific condition or combination of
conditions.

Sr.No. Operator & Description

AND
1 The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.

NOT
2 The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR
3
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

SQL Bitwise Operators


Operator Description
& Bitwise AND

| Bitwise OR
^ Bitwise exclusive OR
select * from emp;
delete from emp;
desc emp;
create table department(deptno int primary key,dname varchar(25)not null,city varchar(25)); desc
department;
insert into department values(1,'Accounts','Mumbai');
create table emp1(empno number(3) primary key,ename varchar(30) not null,deptno number(3)
references department(deptno)); select * from department;
select * from emp1; desc emp1; desc employee; select * from employee; drop table
employee; create table employee(empno number(4) primary key,ename varchar(25)not
null,job varchar(25),hiredate date,salary number(7),comm number (4),deptno
number(2)); insert into employee values(101,'Ashish Deshpande','manager','10-apr-
00',20000,500,1); select * from employee;

SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of the query.


name given to table or column at runtime is called as table alias;

Alias Column Syntax


SELECT column_name AS alias_name

FROM table_name; Alias


Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
ex:
select ename, salary+comm as"salcomm" from employee where empno=101; here
“salcomm” is column name given at runtime.
select * from employee;
select ename, salary+comm as"salcomm" from employee where empno=101;
select ename,salary+comm from employee where empno=101; select salary
,salary*0.10 from employee; select empno,ename,deptno from employee
where deptno=2; select empno,ename,deptno from employee where
deptno!=2; select * from employee where salary>=20000; select * from
employee where salary<20000; select * from employee where salary!=20000;
select * from employee where salary>15000 and comm>5000; select * from
employee where deptno=5 or salary>20000; select * from employee where
deptno not like 2;

Set Operators:-
Set operators are the special operators which combines the result of two queirs.
Following are the set oprators.
1) Union 2) Union all 3) Intersect and 4) Minus.
1) Union operator;
It is used to show all distinct values from two tables.
Ex:- select deptno from employee union select deptno from department; 2)
Union all :- It combines all records from both the tables.

Ex:- select deptno from employee union all select deptno from department;
3) Intersect:-
It is used to find out the common records from the tables by eliminating duplications of the rows.
Ex;- select deptno from employee intersect select deptno from department;

4) Minus:- It is used to finds out the difference between the rows which are present in one table but not
in another table.
Ex:- select deptno from department minus select deptno from employee;

Range Searching Operators:-

1.Between operators is used to get the values from a particular range of values.
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

Syntax: SELECT column_name(s)


FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Ex.
We can display employee record whose department range is between 3 to 6
Select * from employee where deptno between 3 and 6;

2.NOT BETWEEN
To display the products outside the range of the previous example, use NOT BETWEEN:

Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as the
suppliers:

Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
Try it Yourself
»
Patterns matching Operators:
Like operators is used alone or it can be used with NOT keyword.

The SQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

• % - The percent sign represents zero, one, or multiple characters


• _ - The underscore represents a single character
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question
mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
The following SQL statement selects all customers with a CustomerName starting with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Try it Yourself
»

The following SQL statement selects all customers with a CustomerName ending with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

The following SQL statement selects all customers with a CustomerName that have "r" in
the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

The following SQL statement selects all customers with a CustomerName that starts with
"a" and are at least 3 characters in length:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

The following SQL statement selects all customers with a ContactName that starts with "a"
and ends with "o":

Example
SELECT * FROM Customers WHERE
ContactName LIKE 'a%o';
Try it Yourself
»

The following SQL statement selects all customers with a CustomerName that have "or" in
any position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

The following SQL statement selects all customers with a CustomerName that does NOT
start with "a":

Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
All the wildcards can also be used in combinations!

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

Finds any values that starts with "a"


WHERE CustomerName LIKE
'a%'

WHERE CustomerName LIKE Finds any values that ends with "a"
'%a'

Finds any values that have "or" in any position


WHERE CustomerName LIKE
'%or%'
Finds any values that have "r" in the second position
WHERE CustomerName LIKE
'_r%'

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' characters in length

WHERE ContactName LIKE Finds any values that starts with "a" and ends with "o"
'a%o'
Chapter 3. Interactive SQl and Advance
SQL: SQL Performance Tuning
Oracle Function
A function is a subprogram that is used to return a single value. You must declare and
define a function before invoking it. It can be declared and defined at a same time or can
be declared first and defined later in the same block.
Functions once written can be called many times when ever required.
Two types of Functions
1. User Defined Functions
2. Readymade Functions.
SQL supports two types of readymade functions known as single row functions and group
functions.
Single Row Functions
Single-row functions return a single result row for every row of a queried table or view. These
functions can appear in select lists, WHERE clauses, START WITH and CONNECT BY clauses,
and HAVING clauses.
3.1 Inbult Functions
3.1.1 String Functions:
String functions operate on the string values or character values.
There are following string related functions
a) Lower(string)- The Oracle/PLSQL LOWER function converts all letters in the
specified string to lowercase

Syntax:- LOWER( string1 )

Ex :-select lower(‘PHOENIX’)from dual;


Output:-phoenix
If we want to display ename column from employee table in lower case
Select lower(ename)from employee;
b) Upper(String)- The Oracle/PLSQL UPPER function converts all letters in the
specified string to uppercase.
The syntax for the UPPER function in Oracle/PLSQL is:

Syntax: - UPPER (string1)

Ex:-select upper (‘phoenix’) from dual;


Output:- PHOENIX
If we want to display ename column from employee table in lower case
Select upper (ename) from employee;
c) INITCAP (string):- The Oracle/PLSQL INITCAP function sets the first character in
each word to uppercase and the rest to lowercase.
Syntax:-INITCAP( string1 )

Ex:- select initcap(ename)from employee;


d) LPAD(char1,n,char2):- The Oracle/PLSQL LPAD function pads the left-side of a
string with a specific set of characters (when string1 is not null).
Syntax :- LPAD( string1, padded_length ,pad_string)

Where string1(char1)
The string to pad characters to (the left-hand side).
padded_length(n)
The number of characters to return. If the padded_length is smaller than the
original string, the LPAD function will truncate the string to the size
of padded_length.
pad_string(char2)
Optional. This is the string that will be padded to the left-hand side of string1. If
this parameter is omitted, the LPAD function will pad spaces to the left-side
of string1.
Ex:- select lpad(‘Phoenix’,10,’*’)from dual;
Output:-***Phoenix
e) RPAD(Char1,n,char2):- The Oracle/PLSQL RPAD function pads the right-side of
a string with a specific set of characters (when string1 is not null).
Syntax:- RPAD( string1, padded_length , pad_string )

Where string1(char1)
The string to pad characters to (the left-hand side).
padded_length(n)
The number of characters to return. If the padded_length is smaller than the
original string, the LPAD function will truncate the string to the size
of padded_length.
pad_string(char2)
Optional. This is the string that will be padded to the left-hand side of string1. If
this parameter is omitted, the RPAD function will pad spaces to the Right-side
of string1.
Ex:- select rpad(‘Phoenix’,10,’*’)from dual;
Output:-Phoenix***
f) LTRIM(String,chars):- The Oracle/PLSQL LTRIM function removes all specified
characters from the left-hand side of a string.
Syntax:-LTRIM( string1 , trim_string] )

Where
string1
The string to trim the characters from the left-hand side.
trim_string
Optional. The string that will be removed from the left-hand side of string1. If this
parameter is omitted, the LTRIM function will remove all leading spaces
from string1.
Ex:- select ltrim(‘Phoenix’,’p’) from dual;
Output:- hoenix
g) RTRIM(String, Chars): The Oracle/PLSQL RTRIM function removes all specified
characters from the right-hand side of a string.

Syntax:-RTRIM( string1 , trim_string )

Where
string1
The string to trim the characters from the right-hand side.
trim_string
Optional. The string that will be removed from the right-hand side of string1. If
this parameter is omitted, the LTRIM function will remove all leading spaces
from string1.
Ex:- select ltrim(‘Phoenix’,’x’) from dual;
Output:- Phoeni
h) TRIM()The Oracle/PLSQL TRIM function removes all specified characters either
from the beginning or the end of a string.
Removes all spaces from string (beginning and trailing)

Syntax;-TRIM( LEADING | TRAILING | BOTH trim_character FROM string1 )

Where LEADING
The function will remove trim_character from the front of string1.
TRAILING
The function will remove trim_character from the end of string1.
BOTH
The function will remove trim_character from the front and end of string1.
trim_character
The character that will be removed from string1. If this parameter is omitted, the
TRIM function will remove space characters from string1.
string1
The string to trim.
Ex;- Select trim(‘ Phoenix ‘) from dual;
Output:- Phoenix

Ex:-TRIM(' tech ')


Result: 'tech'

TRIM(' ' FROM ' tech ')


Result: 'tech'

TRIM(LEADING '0' FROM '000123')


Result: '123'

TRIM(TRAILING '1' FROM 'Tech1')


Result: 'Tech'

TRIM(BOTH '1' FROM '123Tech111')


Result: '23Tech'

i) Translate(string, from ,to):- The Oracle/PLSQL TRANSLATE function replaces


a sequence of characters in a string with another set of characters. However, it
replaces a single character at a time.

Syntax:-TRANSLATE( string1, string_to_replace, replacement_string )

Where string1
The string to replace a sequence of characters with another set of characters.
string_to_replace(from)
The string that will be searched for in string1.
replacement_string(to)
All characters in the string_to_replace will be replaced with the corresponding
character in the replacement_string.
Ex:- select translate(‘jack’,’j’,’b’) from dual;
Output:- back
j) Repalce(string, search string, replace string):- The Oracle/PLSQL
REPLACE function replaces a sequence of characters in a string with another set of
characters.

Syntax:-REPLACE( string1, string_to_replace , replacement_string)

Ex:-select replace(‘jack and jue’,’j’,’bl’)


Outpur:- b;ack and blue
k) Length(string):- The Oracle/PLSQL LENGTH function returns the length of the
specified string.

Syntax:-LENGTH( string1 )

Ex:- select length(‘phoenix’) from dual;


Output:-7
l) SUBSTR(String,m,n):- The Oracle/PLSQL SUBSTR functions allows you to
extract a substring from a string.

Syntax:-SUBSTR( string, start_position , length )

Where string
The source string.
start_position
The starting position for extraction. The first position in the string is always 1.
length
Optional. It is the number of characters to extract. If this parameter is omitted, the
SUBSTR function will return the entire string.
Ex:- select substr(‘ Phoenix Infotech’,5,7) from dual;
Output:-nix inf
m) SOUNDEX(string1):- The Oracle/PLSQL SOUNDEX function returns a phonetic
representation (the way it sounds) of a string.

Syntax:-SOUNDEX( string1 )

Ex:- select ename from employee where soundex(ename)=soundex(‘asis deshpande’);


3.1.2Arithmetic Functions

Arithmetic functions called as numeric functions that operate on numbers.


Following are the arithmetic functions used in oracle
1) ABS:-returns the absolute value of a number.
It converts negative value to positive value

Syntax:-ABS( number )

Ex:- select abs(-25) from dual;


Output:- 25
2) Power(m,n):- it will find the power to the number n.
The Oracle/PLSQL POWER function returns m raised to the nth power.

Syntax:-POWER( m, n )

Where m The base used in the calculation.


N The exponent used in the calculation
Ex:-select power(4,2) from dual;
Output:-16
3) Round():-The Oracle/PLSQL ROUND function returns a number rounded to a certain
number of decimal places.

Syntax:-ROUND( number , decimal_places)

Ex:-select round(100.256,2) from dual;


Output:-100.25
4) SQRT(n):- The Oracle/PLSQL SQRT function returns the square root of n.

Syntax:-SQRT( n )

Ex:-select sqrt(25)from dual;


Output:- 5
5) Ceil(n):- The Oracle/PLSQL CEIL function returns the smallest integer value that is
greater than or equal to a number.

Syntax:-CEIL( number )

Ex:- select ceil(48.76) from dual;


Output:-49
6) Greatest(exp1,exp2,expn):- returns the greatest value in a expressions.

Syntax:- GREATEST( expr1 , expr2, ..., expr_n )

Ex:- select greatest(4,5,17)from dual


Output:- 17
7) Least(exp1,exp2,expn):- returns the lowest value in a list of expresions.

Syntax:- LEAST( expr1 [, expr2, ... expr_n] )

Ex:- Ex:- select least(4,5,17)from dual


Output:- 4

8) Exp(n):- The Oracle/PLSQL EXP function returns e raised to the nth power, where e =
2.71828183.

Syntax:-exp( number )
Ex:- select exp(3) from dual;

Output:- 20.0855369231877

9) Floor(n):- The Oracle/PLSQL FLOOR function returns the largest integer value that is
equal to or less than a number.

Syntax:-FLOOR( number )

Ex:- select floor(48.879) from dual;


Output:- 48
10) Log(m,n):- The Oracle/PLSQL LOG function returns the logarithm of n base m.

Syntax:-LOG( m, n )

Ex:- select log(100,10) from dual;


Output:-5
11) Mod(m,n):- The Oracle/PLSQL MOD function returns the remainder of m divided
by n.

Ex:- MOD( m, n )

Ex:- select mod(500,2) from dual;


Output:-0
12) Sign(n):- The Oracle/PLSQL SIGN function returns a value indicating the sign of a
number.

Ex:-SIGN( number )

Ex:- select sign(-22)from dual;


Output:- -1
If number < 0, then the SIGN function returns -1.
If number = 0, then the SIGN function returns 0.
If number > 0, then the SIGN function returns 1.
13) sin (n):-The Oracle/PLSQL SIN function returns the sine of n.

syntax:-SIN( n )

Ex:-select SIN(3)from dual;


Result: 0.141120008059867

14) Trunc(a,b):- The Oracle/PLSQL TRUNC function returns a number truncated to a


certain number of decimal places.

Syntax:-TRUNC( number , decimal_places )

number
The number to truncate.
decimal_places
Optional. The number of decimal places to truncate to. This value must be an
integer. If this parameter is omitted, the TRUNC function will truncate the number
to 0 decimal places.
Ex:-TRUNC(125.815)
Result: 125
Ex:-TRUNC(125.815, 0)
Result: 125
Ex:-TRUNC(125.815, 1)
Result: 125.8
Ex;-TRUNC(125.815, 2)
Result: 125.81
3.2.1 Date and Time Functions:-
Date functions are used to deal with the date type of columns from the table as well as
general date values.
These functions generally return the date type of value.only months_between return
numerical values.
Following are the date functions
1) Add_months(d,n):- The Oracle/PLSQL ADD_MONTHS function returns a date with a
specified number of months added.

Syntax:-ADD_MONTHS( d, n )

Where d means date and n means number of months


Ex:- select add_months(sysdate,2) from dual;
Output:- 22-dec-2020
Select hiredate,add_months(hiredate,3) from employee;
Output:- it will add 3 months in hiredate column value for each employee and disply.

ADD_MONTHS('01-Aug-03', 3)
Result: '01-Nov-03'

2) Last_day(date) :-The Oracle/PLSQL LAST_DAY function returns the last day of the
month based on a date value.

Syntax:-LAST_DAY( date )

Ex:- select last_day(’19-mar-2020’)from dual;


Output:- 31-mar-2020
Ex;- select ename,hiredate,last_day(hiredate) from employee;
3) Months_betwwendate1,date2);- The Oracle/PLSQL MONTHS_BETWEEN function
returns the number of months between date1 and date2.
it find outs the month difference in franction values also.

Syntax:-MONTHS_BETWEEN( date1, date2 )

Ex;-select months_between(’17-jul-2013’,sysdate)from dual;


Output:- 2.5088369
Select ename,hiredate,months_between(sysdate,hiredate)from employee;
4) Next_day(date,day):- The Oracle/PLSQL NEXT_DAY function returns the first
weekday that is greater than a date.

Syntax:-NEXT_DAY( date, weekday )

Ex:- select next_day(’22-oct-2020’,’Friday’) from dual;


Output :- 23-oct-2020.in the output the date on Friday after 22-oct-2020 is displayed

3.2.2 Aggregate Functions:-


Aggregate functions are also known as Group functions.
These functions returns a result based on a group of rows.
To find out single value results like sum of salries,counting number of employees,finding
maximum,minimum values these operations can be done using these functions.
Following are the aggregate functuions
1) Avg(column):- The Oracle/PLSQL AVG function returns the average value of a column by
the expression.

Syntax:- SELECT AVG(columnname)FROM table WHERE conditions;

Ex:- select avg(salary)from employee;


It will display average salary of all employee table.
2) Count(*):-The Oracle/PLSQL COUNT function returns the count of an expression. Or it
will count all rows from the specified table or view.
Ex:-select count (* ) from employee;
Display number of rows from the table.
3) Count(expression/column):-counts the rows defined by the expression or column.
ex:- select count(comm)from employee;
display the total values present in particular column.
4) Min(expression):-The Oracle/PLSQL MIN function returns the minimum value from a
column by the expression.
Ex:- select min(salary)from employee;
Output: display minimum salary from employee table.
5) Max(expression) find the maximum values from a column by the exression.
Ex:- select max(salary)from employee;
Output:- display the maximum salary from employee table.
6) Sum(expression):- computes the sum of column values by the expression
Ex:-select sum(salary)from employee;
Output:- display total of salary colum,8n.
///////////Sample quries////////////
///////////////StringFunctions///////////
select lower('PHOENIX') from dual;
select upper('phoenix') from dual;
select initcap('phoenix')from dual;
select lpad('Phoenix',10,'*')from dual;
select rpad('Phoenix',10,'*')from dual;
select ltrim('phoenix','p') from dual;
select rtrim('Phoenix','x') from dual;
select translate('jack','j','b') from dual;
select length('database management system') from dual;
select substr('Phoenix Infotech',6,7)from dual;
select ename from employee;
select upper(job) from employee;
select lower(ename) from employee;
select ename from employee where soundex(ename)=soundex('Asis Deshpande');
select * from employee;
//////////////Arithmetic functions////////////
select abs(-25)from dual;
select power(4,3) from dual;
select round(100.256)from dual;
select round(100.256,2)from dual;
select sqrt(25) from dual;
select ceil(48.76) from dual;
select greatest(4,5,17)from dual;
select least(4,5,17)from dual;
select exp(3) from dual;
select floor(48.789)from dual;
select log(100,10)from dual;
select mod(10,2)from dual;
select mod(11,2)from dual;
select sign(-3)from dual;
select sign(3)from dual;
select sign(0)from dual;
select sin(3)from dual;
select trunc(125.825)from dual;
select trunc(125.825,2)from dual;
select trunc(125.825,1)from dual;
/////////////datetime functions////////////
select sysdate from dual;
select add_months(sysdate,4)from dual;
select last_day(sysdate)from dual;
select ename,hiredate,last_day(hiredate)as "lastday"from employee;
select ename,hiredate,add_months(hiredate,2)as "lastday"from employee;
select months_between('12-oct-2020',sysdate)from dual;
select months_between(sysdate,'12-aug-2020')from dual;
select ename,hiredate,months_between(sysdate,hiredate)from employee;
select next_day('22-oct-2020','tuesday')from dual;
//////////////////aggregate functions//////////
select avg(salary)from employee;
select count(*)from employee;
select count(comm)from employee;
select min(salary)from employee;
select max(salary)from employee;
select sum(salary)from employee;
select * from employee;

3.3 Group By Clause

The Oracle GROUP BY clause is used in aSELECT statement to collect data


across multiple records and group the results by one or more columns.
It helps to arrange similar data into groups. It is also used with SQL functions to
group the result from one or more tables.
Syntax:-
SELECT column1, column2, ... ,column n,
aggregate_function (aggregate_column)
FROM tables
WHERE conditions
GROUP BY column1,column2, ... column n;

Where column1, column2, ... ,column n


The columns that are not encapsulated within an aggregate function and must be
included in the GROUP BY clause.
aggregate_function
It can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.
aggregate_column This is the column or expression that the aggregate_function will
be used on.
tables
The tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
Ex:- select deptno,avg(salary)from employee group by
deptno;
This will display average salary from employee table deptno
wise.
Select job,count(*) from employee group by job;
This is to count number of employee working in each
department.
Select deptno,sum(salary)from employee group by deptno;
This will display sum of salary deptno wise.
Select job,max(salary)from employee group by job;
This will display job wise maximum salary.
3.4 Having Clause
The Oracle HAVING clause is used in combination with the GROUP BY clause to restrict
the groups of returned rows to only those whose the condition is TRUE.
Having clause use to execute the summary query.
Syntax:
SELECT column1, column2, ... column n,
aggregate_function (aggregate_column)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column n
HAVING having_condition;

Where column1, column2, ... column n


The expressions that are not encapsulated within an aggregate function and
must be included in the GROUP BY clause.
aggregate_function
It can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.
aggregate_column
This is the column or expression that the aggregate_function will be used
against.
tables
The tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.
WHERE conditions
Optional. These are the conditions for the records to be selected.
having_condition
This is a further condition applied only to the aggregated results to restrict the
groups of returned rows. Only those groups whose condition evaluates to TRUE
will be included in the result set.

Ex:- select deptno,sum(salary)from employee group by deptno


having deptno=2;
select deptno,sum(salary)from employee group by deptno having
deptno in(2,3);
select job,count(*)as "Total EMP" from employee group by job
having avg(salary)>15000;
Difference between Where and Having Clause
Sr. Key Where Having
No.

1 Definition WHERE clause in SQL query specifies The WHERE clause is


search conditions for the rows returned used to specify the
by the it and limits rows to a specific row- required condition (on
set. In case if user wants to get the aggregate values) while
particular records based on some specific selecting the rows of a
classification or condition then using table.
‘where’ clause is useful.

2 Execution As per the order of execution of clauses, On other hand HAVING


the WHERE clause is executed before clause is executed after
the execution of the GROUPBY CLAUSE groups are created.
and, after the execution of the FROM
clause.

3 GroupBy WHERE clause can be used with On other hand, Having


compatibility GroupBy clause in a SQL query. clause does not have
compatibility with
GroupBy clause.

4 Row WHERE clause select the rows before On other hand Having
selection grouping of result. clause selects the rows
after grouping.

5 Aggregate WHERE clause cannot contain the On other hand HAVING


Function aggregate function. clause can contain the
aggregate function.
3.5 Order By Clause
The Oracle ORDER BY clause is used to sort the records in your result set. The ORDER
BY clause can only be used in SELECT statements.
To arrange the displayed rows in ascending or descending order on given field/column
Syntax;
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression ASC | DESC;

Where :
expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one
table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ASC
Optional. It sorts the result set in ascending order by expression (default, if no
modifier is provider).
DESC
Optional. It sorts the result set in descending order by expression.

If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will
be sorted by expression in ascending order
Ex:- Select * from employee order by ename;
Display the records ascending order by ename
Select * from employee order by ename desc;
Display the records descending order by ename.

Sub Queries
A subquery is best defined as a query within a query. Subqueries enable you to write
queries that select data rows for criteria that are actually developed while the query is executing
at run time. More formally, it is the use of a SELECT statement inside one of the clauses of
another SELECT statement. In fact, a subquery can be contained inside another subquery, which
is inside another subquery, and so forth. A subquery can also be nested inside INSERT,
UPDATE, and DELETE statements. Subqueries must be enclosed within parentheses.

The inner Query gets executed first, then the output on inner query is given to outer
query.
A subquery can be used any place where an expression is allowed providing it returns a
single value. This means that a subquery that returns a single value can also be listed as an object
in a FROM clause listing. This is termed an inline view because when a subquery is used as part
of a FROM clause, it is treated like a virtual table or view. Subquery can be placed either in
FROM clause, WHERE clause or HAVING clause of the main query.

Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit
for nesting subqueries expressed in a FROM clause.In practice, the limit of 255 levels is not
really a limit at all because it is rare to encounter subqueries nested beyond three or four levels.

A subquery SELECT statement is very similar to the SELECT statement used to begin a regular
or outer query.The complete syntax of a subquery is:

EX:- select * from employee where deptno=(select deptno from employee where
ename='arun patil');
Types of Subqueries

Single Row Sub Query: Sub query which returns single row output. They mark the usage of
single row comparison operators, when used in WHERE conditions.

Multiple row sub query: Sub query returning multiple row output. They make use of multiple
row comparison operators like IN, ANY, ALL. There can be sub queries returning multiple
columns also.

Correlated Sub Query: Correlated subqueries depend on data provided by the outer query.This
type of subquery also includes subqueries that use the EXISTS operator to test the existence of
data rows satisfying specified criteria.

Single Row Sub Query

A single-row subquery is used when the outer query's results are based on a single, unknown
value. Although this query type is formally called "single-row," the name implies that the query
returns multiple columns-but only one row of results. However, a single-row subquery can return
only one row of results consisting of only one column to the outer query.

In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.

SELECT first_name, salary, department_id FROM employees WHERE salary =


(SELECT MIN (salary)FROM employees);

A HAVING clause is used when the group results of a query need to be restricted based on some
condition. If a subquery's result must be compared with a group function, you must nest the inner
query in the outer query's HAVING clause.

SELECT department_id, MIN (salary)


FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary)
FROM employees)
Multiple Row Sub Query

Multiple-row subqueries are nested queries that can return more than one row of results to the
parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING
clauses. Since it returns multiple rows,it must be handled by set comparison operators (IN, ALL,
ANY).While IN operator holds the same meaning as discussed in earlier chapter, ANY operator
compares a specified value to each value returned by the sub query while ALL compares a value
to every value returned by a sub query.

Correlated Sub Query

As opposed to a regular subquery, where the outer query depends on values provided by the
inner query,a correlated subquery is one where the inner query depends on values provided by
the outer query. This means that in a correlated subquery,the inner query is executed repeatedly,
once for each row that might be selected by the outer query.

Correlated subqueries can produce result tables that answer complex management questions.

Consider the below SELECT query. Unlike the subqueries previously considered, the subquery
in this SELECT statement cannot be resolved independently of the main query. Notice that the
outer query specifies that rows are selected from the employee table with an alias name of e1.
The inner query compares the employee department number column (DepartmentNumber) of the
employee table with alias e2 to the same column for the alias table name e1.

SELECT EMPLOYEE_ID, salary, department_id


FROM employees E WHERE salary > (SELECT AVG(salary) FROM EMP T
WHERE E.department_id = T.department_id)
Views
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.
o View is very useful in maintain the security of database.

You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.
CREATE VIEW command allows user to create a view

Syntax
CREATE VIEW view_name AS SELECT column1, column2, ....,column n
FROM table_name
WHERE condition;
You can include multiple tables in your SELECT statement in a similar way as you use
them in a normal SQL SELECT query.
To show view data
Syntax:-select * from viewname;
Ex: - select * from emp_view;

1. Creating view having all records and all fields from existing
table

Syntax: - create view viewname as select * from tablename;


Ex:-create view emp_view3 as select * from employee;
After executing this it will create view with all record and fields.

2. Creating view having specific fields but all the records from
existing table
Syntax: - create view viewname as select columnname1,
columnname2,……., columnname n from tablename;
Ex:-create view emp_view as select ename, job, salary from employee;
After executing this emp_view will be created with all records with specific fields.
3. Creating view having specific records but all the fields from
exiting table
Syntax:- create view viewname as select * from tablename
where condition;
Ex:-create view emp_view2 as select * from employee where salary>15000;
1. Insert record in view: Insert command is used to insert record in view.
Syntax:
Insert into viewname values (‘v1’,’v2’,’v3’,’v4’,…….,’vn’);

Ex:- insert into stu_view values(6,'dinesh','beed',26);

2. Updating Views: Update query is used to update the records of view.


Updating in view reflects the original table also.
Syntax:-
1. Update viename set fieldname =newvalue ;
2. Update viename set fieldname =newvalue where condition;
Ex:-1.Update stu_view set age=25;
In this age of all students updated to 25 in stu_view and student table also.
2. Update stu_view set age =26 where rollno=1;
In this age of rollno 1 is updated in stu_view and student table also.
3. Dropping Views: Views can be dropped by using drop view command
Syntax: - drop view viewname;
Ex: - drop view stu_viewname;
4. Delete record from views:
Delete operation can be performed on the table through view
Syntax:
1. Delete from viewname;
2. Delete from viewname where condition;
Ex:-1.delete from stu_view;
3. Delete from stu_view where rollno=5;
Sequences:-
A sequence is a set of integers 1, 2, 3, ... ,n that are generated in order on demand. Sequences are
frequently used in databases because many applications require each row in a table to contain a unique
value and sequences provide an easy way to generate them.

Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which
multiple users may generate unique integers. You can use sequences to automatically generate
primary key values.

After a sequence is created, you can access its values in SQL statements with the CURRVAL
pseudocolumn, which returns the current value of the sequence, or the NEXTVAL pseudocolumn,
which increments the sequence and returns the new value.

Syntax:

CREATE SEQUENCE sequencename START WITH initial_value INCREMENT BY


increment_value MINVALUE minimum value MAXVALUE maximum value
CYCLE|NOCYCLE;

Where

sequencename: Name of the sequence.

initial_value: starting value from where the sequence starts.

Initial_value should be greater than or equal to minimum value and less than equal to maximum
value.

increment_value: Value by which sequence will increment itself.

Increment_value can be positive or negative.

minimum_value: Minimum value of the sequence.

maximum_value: Maximum value of the sequence.

cycle: When sequence reaches its set_limit it starts from beginning.

nocycle: An exception will be thrown if sequence exceeds its max_value.


Example 1:
CREATE SEQUENCE sequence_1 start with 1 increment by 1 minvalue 0 maxvalue
100
cycle;
Above query will create a sequence named sequence_1.Sequence will start from 1 and will be
incremented by 1 having maximum value 100. Sequence will repeat itself from start value after exceeding
100.
Example to use sequence : create a table named students with columns as id and name.
CREATE TABLE students
(
ID number(10),
NAME char(20)
);

Now insert values into table

INSERT into students VALUES(sequence_1.nextval,'Ramesh');


INSERT into students VALUES(sequence_1.nextval,'Suresh');

where sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.

Altering Sequence
The sequence can be altered using alter sequence command.

Syntax:-
Alter sequence sequencename variable value;
Ex:-alter sequence sequence_1 maxvalue 200;

Dropping sequence
Sequence can be dropped using drop sequence command as follows
Syntax:
Drop sequence sequencename;
Ex:-drop sequence sequence_1;
After executing this command sequence will be dropped from database.
SYNONYM
Synonyms is an alternative name for a table, view, sequence, procedure, stored function etc for the
users convenience to use it.

They are used to make it easy for users to access database objects owned by other users.
a synonym is an alias or alternative name for a database object such as a
table, view, stored procedure, user-defined function, and sequence. A synonym
provides you with many benefits if you use it properly.
Use the CREATE SYNONYM statement to create a synonym.
Syntax:

CREATE SYNONYM synonymname


FOR databasename.objectname;
Ex:- create synonym emp for hr.employee;
To show record from synonym
Syntax:
Select * from synonymname;
Ex:- select * from emp;
Dropping Synonym
It is used to drop the synonym.
Drop synonym synonymname;
Ex:- Drop synonym emp;
Ex:-
create synonym empl for employee;
select * from empl;
select * from employee;
select * from emp_view;
create synonym e for emp_view;
select * from e;
drop synonym e;
Indexes
An index is a performance-tuning method of allowing faster retrieval of records. An index
creates an entry for each value that appears in the indexed columns. Each index name must be
unique in the database.
An index is a pointer to data in a table. It is similar to alphabetical index of a book present at the
end of book.
An index is used to speed up select queries and also where clause.
You can create an index in SQL using the CREATE INDEX statement.

Types of indexes:-
1. Simple Index.
2. Composite Index
3. Unique Index
4. Implicit Index
1. Simple Index
This index is created on a single column of a table.

Syntax

The syntax to create an index in SQL is:

CREATE INDEX index_name ON table_name (column1);

Ex: - Create index ind1 on student (rollno);

2. Composite Index
This index created on a multiple columns of a table.

Syntax

The syntax to create an index in SQL is:

CREATE INDEX index_name ON table_name (column1, column2, ... column_n);

Ex:- Create index ind2 on student (sname,age);


3. Unique Index
A unique index does not allow any duplicate values to be inserted into the
table.

Syntax

The syntax to create an index in SQL is:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ... column_n);

Ex:- create unique index ind3 on student(sname);

4. Implicit Index
Implicit index are indexes that are automatically created by the database server
when an object is created.
Such indexes are created for primary key and unique key.

Syntax

The syntax to show an index in SQL is:

Show index from tablename;

Ex:- show index from student;

Dropping Index:-

To remove index from database object you can use the drop index command
Syntax:-
Drop index indexname;

Ex:-drop index ind1;


Join
The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values common to
each.
There are the different types of the JOINs in SQL as

1. INNER JOIN: Returns records that have matching values in both tables

2. LEFT OUTER JOIN: Returns all records from the left table, and the matched
records from the right table

3. RIGHT OUTER JOIN: Returns all records from the right table, and the
matched records from the left table

4. FULL OUTER JOIN: Returns all records when there is a match in either left
or right table

5. Self Join: join a table to itself as if the table were two tables.

1. INNER JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as
the condition satisfies. This keyword will create the result-set by combining all
rows from both the tables where the condition satisfies i.e value of the common
field will be same.

Syntax:
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 INNER JOIN table2 ON table1.matching_column =
table2.matching_column;
table1: First table.
table2: Second table.
matching column: Column common to both the tables.
Ex: - SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM
Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

2.Left Outer Join:


This join returns all the rows of the table on the left side of the join and matching
rows for the table on the right side of join. The rows for which there is no matching row
on right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER
JOIN.
Syntax:

SELECT table1.column1, table1.column2, table2.column1,..,


FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Where
table1: First table.
table2: Second table
matching_column: Column common to both the
tables.

We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.

Ex:- SELECT Student.NAME,StudentCourse.COURSE_ID


FROM Student LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
3.Right Outer Join:
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table
on the right side of the join and matching rows for the table on the left side of join. The
rows for which there is no matching row on left side, the result-set will contain null.
RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:

SELECT table1.column1, table1.column2, table2.column1,…..


FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Where
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are same.

Ex:-SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
4.Full Outer Join:-

FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both the tables. The rows for which
there is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2, 95table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Where
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

Ex:-SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

5. Self Join:
As the name signifies, in SELF JOIN a table is joined to itself. That is, each row
of the table is joined with itself and all other rows depending on some conditions. In
other words we can say that it is a join between two copies of the same table.
Syntax:

SELECT a.coulmn1 , b.column2 FROM table_name a, table_name b


WHERE some_condition;
Where table_name: Name of the table.
some_condition: Condition for selecting the rows.
Ex:-

SELECT a.ROLL_NO , b.NAME


FROM Student a, Student b
WHERE a.ROLL_NO < b.ROLL_NO;

Consider two tables


1. Student

2. StudentCourse
1. Inner Join:-

Ex:-SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Output:

2.Left Outer Join:


Ex:-

SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student


LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
3.Right Outer Join:
Ex: -

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output

4.Full Outer Join


Ex:-

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output
5.Self join:
Ex:-

SELECT a.ROLL_NO , b.NAME


FROM Student a, Student b
WHERE a.ROLL_NO < b.ROLL_NO;

Outpout
Chapter 4 PL/SQL Programming

4.1 Introduction to PL/SQL


PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.

PL/SQL stands for “Procedural Language extensions to the Structured Query


Language”. SQL is a popular language for both querying and updating data in the relational
database management systems (RDBMS).

PL/SQL adds many procedural constructs to SQL language to overcome some limitations
of SQL. Besides, PL/SQL provides a more comprehensive programming language solution
for building mission-critical applications on Oracle Databases.

PL/SQL is a highly structured and readable language.

PL/SQL is a completely portable, high-performance transaction-processing language.

PL/SQL provides a built-in, interpreted and OS independent programming environment.

Features of PL/SQL
PL/SQL has the following features −

 PL/SQL is tightly integrated with SQL.


 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.
 It supports object-oriented programming.
 It supports the development of web applications and server pages.

4.1.1 Advantages of PL/SQL

PL/SQL has the following advantages –

 Tight Integration with SQL-PL/SQL is tightly integrated with SQL, the most widely used
database manipulation language. PL/SQL lets you use all SQL data manipulation, cursor
control, and transaction control statements, and all SQL functions, operators, and
pseudocolumns.PL/SQL fully supports SQL data types.

 Block Structure- PL/SQL consist of blocks of code which can be nested within each
other.
 High Performance-PL/SQL lets you send a block of statements to the database,
significantly reducing traffic between the application and the database.
 High Productivity-PL/SQL lets you write compact code for manipulating data. Just as a
scripting language like PERL can read, transform, and write data in files, PL/SQL can
query, transform, and update data in a database.
 Portability-You can run PL/SQL applications on any operating system and platform
where Oracle Database runs.
 Scalability-PL/SQL stored subprograms increase scalability by centralizing application
processing on the database server. The shared memory facilities of the shared server let
Oracle Database support thousands of concurrent users on a single node.
 Manageability-PL/SQL stored subprograms increase manageability because you can
maintain only one copy of a subprogram, on the database server, rather than one copy
on each client system.
 Support for Object-Oriented Programming-PL/SQL supports object-oriented
programming with "Abstract Data Types".
 Support for Developing Web Applications-PL/SQL lets you create applications that
generate web pages directly from the database, allowing you to make your database
available on the Web and make back-office data accessible on the intranet.
 Support for Developing Server Pages-PL/SQL Server Pages (PSPs) let you develop web
pages with dynamic content. PSPs are an alternative to coding a stored subprogram that
writes the HTML code for a web page one line at a time.
 Error Handling- PL/SQL handles exceptions effectively during the execution of PL/SQL
 Procedural language Capability-PL/SQL includes procedural language constructs such
as conditional statements and looping constructs.

4.1.2 PL/SQL Block Structure


PL/SQL which is a block-structured language; this means that the PL/SQL programs are
divided and written in logical blocks of code. The parts of PL/SQL block structure are as
1. Declaration 2. Execution 3. Exception

DECLARE
declaration statements;

BEGIN
executable statements

EXCEPTIONS
exception handling statements

END;
-Declare section starts with DECLARE keyword in which variables, constants, records
as cursors can be declared which stores data temporarily. It basically consists definition
of PL/SQL identifiers. This part of the code is optional.
-Execution section starts with BEGIN and ends with END keyword. This is a mandatory
section and here the program logic is written to perform any task like loops and
conditional statements. It supports all DML commands, DDL commands and SQL*PLUS
built-in functions as well.
-Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can
be handled in this section.
Ex:- 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.

DBMS_OUTPUT.PUT_LINE ();
This statement is used to print the message or values.
Ex:-

declare

i number;

begin

i:=1;

i:=i+1;

dbms_output.put_line('values of i is: '|| i);

end;

/
Output:- values of i is: 2
4.1.3 PL/SQL Execution Environment
The PL/SQL compilation and runtime system is an engine that compiles and runs
PL/SQL units. The engine can be installed in the database or in an application
development tool, such as Oracle Forms.

In either environment, the PL/SQL engine accepts as input any valid PL/SQL unit. The
engine runs procedural statements, but sends SQL statements to the SQL engine in the
database, as shown in Figure 1-1.

Figure 1-1 PL/SQL Engine

Typically, the database processes PL/SQL units.

When an application development tool processes PL/SQL units, it passes them to its local PL/SQL
engine. If a PL/SQL unit contains no SQL statements, the local engine processes the entire PL/SQL
unit. This is useful if the application development tool can benefit from conditional and iterative
control.

For example, Oracle Forms applications frequently use SQL statements to test the values of field
entries and do simple computations. By using PL/SQL instead of SQL, these applications can avoid
calls to the database.
4.1.4 PL/SQL Data Types

PL/SQL variables and constants must have a valid data type. Which specifies storage
format. There are six built-in PL/SQL data types

1. Scalar data types - Scalar data types haven't internal components.


2. Composite data types - Composite data types have internal components to manipulate
data easily.
3. Reference data types - This data types work like a pointer to hold some value.
4. LOB data types - Stores large objects such as images, graphics, video.
5. User Define data types - Define your own data type that inherited from predefined base
data type.
1. Scalar data type – stores Single values with no internal components
Ex:- Numeric, Character, DATETIME, or BOOLEAN.

Numeric Data type stores real nu,bers,floating point numbers,zero and infinity

Number is the most commonly used numeric datatype

Character data type stores character and alphanumeric data in strings.VARCHAR2 is


most commonly used character data type

Other character data types include char,nchar,varchar,long,raw,string etc

Boolean data type

It stores logical values which are TRUE ,FALSE or NULL

DateTime Data type

DateTime stores date and time values with fractional precision of seconds.

Different DateTime datatpyes used includes DATE,TIME,TIMESTAMP etc.

2. % Type Attribute
the variables pf PL/SQL often deal with table columns and thefore should have
the same datatype as the column of the table
a special attribute known as %type allows us to declare a data item of the same
data type as previously declared variable or column.
4.1.5 Variable – variables are used to hold the values. Before using any variable it
needs to be declared in the declaration section of the PL/SQL block
Syntax :-
Variable_name datatype(size);
Ex:- emp_sal number(8);
Initializing variable
Syntax:-
Variable_name := value;
Ex:- emp_sal :=5000;
Scope of variables:
There are 2 types of variables
Local variable and Global variables
Local variables declared in an inner block which can not be referenced by
outside blocks.
Global variables declared in an outer block which can be referenced by itself
and by its inner blocks.
4.1.6 Constants
A constant is a named memory location which holds a value to be
used in a PL/SQl block that remains unchanged throughout the
execution of the program. Constant needs to be declared in the
declaration section
Constantname CONSTANT datatype :=value;
Ex:- pi CONSTANT number(3,2):=3.14;
/////// https://www.tutorialspoint.com/plsql/plsql_constants.htm//////
operators in PL/SQL. An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulation. PL/SQL language is rich in built-in operators and
provides the following types of operators −

 Arithmetic operators

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5


* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

** Exponentiation operator, raises one operand to the A ** B will give


power of other 100000

 Relational operators

Relational operators compare two expressions or values and return a Boolean result.
Following table shows all the relational operators supported by PL/SQL.

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (A = B) is not
=
condition becomes true. true.

!=
Checks if the values of two operands are equal or not, if values are (A != B) is
<>
not equal then condition becomes true. true.
~=

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right (A < B) is true.
<
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true
 Comparison operators

Comparison operators are used for comparing one expression to another. The result is
always either TRUE, FALSE or NULL.

Operator Description Example

The LIKE operator compares a character, If 'Zara Ali' like 'Z% A_i' returns
string, or CLOB value to a pattern and a Boolean true, whereas, 'Nuha
LIKE
returns TRUE if the value matches the Ali' like 'Z% A_i' returns a
pattern and FALSE if it does not. Boolean false.

If x = 10 then, x between 5 and


The BETWEEN operator tests whether a 20 returns true, x between 5
BETWEEN value lies in a specified range. x BETWEEN and 10 returns true, but x
a AND b means that x >= a and x <= b. between 11 and 20 returns
false.

If x = 'm' then, x in ('a', 'b', 'c')


The IN operator tests set membership. x IN
returns Boolean false but x in
IN (set) means that x is equal to any member
('m', 'n', 'o') returns Boolean
of set.
true.

The IS NULL operator returns the


BOOLEAN value TRUE if its operand is
If x = 'm', then 'x is null' returns
IS NULL NULL or FALSE if it is not NULL.
Boolean false.
Comparisons involving NULL values always
yield NULL.
 Logical operators

Following table shows the Logical operators supported by PL/SQL. All these operators
work on Boolean operands and produce Boolean results. Let us assume variable
A holds true and variable B holds false, then –

Operator Description Examples

Called the logical AND operator. If both the operands are true then (A and B) is
and
condition becomes true. false.

Called the logical OR Operator. If any of the two operands is true then (A or B) is
or
condition becomes true. true.

Called the logical NOT Operator. Used to reverse the logical state of not (A and B)
not its operand. If a condition is true then Logical NOT operator will make is true.
it false.

4.2 Control Structure


PL/SQL supports the conditional statements and iterative statements
The control structures decide the execution flow of the program
depending on the conditions defined by the programmer.
Types of Control Structure
1. Selection/ Decision Making Control Structure is used to test a condition
and then executes one sequence of statements instead of another
depending on which condition evaluates to true. IF and Case statements
are used as Selection control statements.

2. Iteration Control Structure is used to executes a sequence of statements


repeatedly as long as a condition true.
3. Sequence Control Structure is the simplest form of control structures
which simply execute a sequence of statements in the order I n which they
occur.
4.2.1 Selection/ Decision Making Control Structure
Decision making statements are those who will decide the flow-control
of SQL statements based on the conditions. It gives the programmer a better control of
preventing a particular code from executing (diagram 1) or choosing a desired code
based on the condition (diagram 2). Below is the pictorial representation of the "Decision
Making Statement".
4.2.1(A) IF Statements
There are 4 types of IF statements
1. IF-Then Statement
2. IF-Then-Else Statement
3. IF-Then Elsif Statement
4. Nested If-Then –Else Statements
1. IF-THEN Statement
An if statements executes a sequence of statements depending on the value of a
condition.
Conditions can be formed using relational operators such as > , < ,>=,<=,=,<>,!=,
like ,between.. and, in,is null etc
IF –THEN executes the statements or a block of statements if the condition return
true.

Syntax

IF condition
THEN
Statement;
END IF;
Example:-
DECLARE
a number(3):=200;
Begin
IF(a<10)Then
dbms_output.put_line(‘a is less than 10’);
End if;
Dbms_output.put_line(‘value of a is : ‘ || a);
End;
/
Output:
value of a is : 200

2. IF-THEN-ELSE Statement
In this type of IF statement there is keyword Else followed by an alternative
sequence of statements which can execute when the condition with if
evaluates to false

Syntax

IF condition
THEN
[Statements to execute when condition is TRUE]
ELSE
[Statements to execute when condition is FALSE]
END IF;
Example:-

IF condition
THEN
Statement;
END IF;
Example:-
DECLARE
a number(3):=200;
Begin
IF(a<10)Then
dbms_output.put_line(‘a is less than 10’);
Else
dbms_output.put_line(‘a is not less than 10’);
End if;
Dbms_output.put_line(‘value of a is : ‘ || a);
End;
/
Output:
a is not less than 10
value of a is : 200

3. IF-THEN-ELSIF statement

This syntax is used to execute one set of statements when condition1 is


TRUE or a different set of statements when condition is FALSE.
The IF-THEN-ELSIF statement is mainly used where one alternative should
be chosen from a set of alternatives, where each alternative has its own
conditions to be satisfied.
The first conditions that return <TRUE> will be executed, and the remaining
conditions will be skipped.
The IF-THEN-ELSIF statement may contain 'ELSE' block in it. This 'ELSE'
block will be executed if none of the conditions is satisfied.

Syntax

IF Condition1 THEN
Statements to execute when condition1 is TRUE
ELSIF condition2
THEN
Statements to execute when condition2 is TRUE
ELSE
Statements
END IF;
If condition1 is not satisfied, then the controller will check for condition2.
The controller will exit from the IF-statement in the following two cases.
When the controller found any condition that returns <TRUE>. In this case, the
corresponding action_block will be executed and the controller will exit this IF-
statement block and will start executing the remaining code.
When none of the conditions satisfied, the then controller will execute ELSE
block if present, then will exit from the IF-statement.
Ex:-1. Without ELSE block

DECLARE
mark NUMBER :=55;
BEGIN
dbms_output.put_line(‘Program started.’ );
IF( mark >= 70) THEN
dbms_output.put_line(‘Grade A’);
ELSIF(mark >= 40 AND mark < 70) THEN
dbms_output.put_line(‘Grade B');
ELSIF(mark >=35 AND mark < 40) THEN
dbms_output.put_line(‘Grade C’);
END IF;
dbms_output.put_line(‘Program completed.’);
END;
/
Output
Program started.
Grade B
Program completed.

2. With ELSE block


DECLARE
mark NUMBER :=25;
BEGIN
dbms_output.put_line(‘Program started.’ );
IF( mark >= 70) THEN
dbms_output.put_line(‘Grade A’);
ELSIF(mark >= 40 AND mark < 70) THEN
dbms_output.put_line(‘Grade B');
ELSIF(mark >=35 AND mark < 40) THEN
dbms_output.put_line(‘Grade C);
ELSE
dbms_output.put_line(‘No Grade’);
END IF;
dbms_output.put_line(‘Program completed.' );
END;
/
Output
Program started.
No Grade
Program completed.
4. NESTED-IF Statement

The NESTED-IF statement is basically allowed programmers to place one or


more 'IF' condition inside another 'IF' condition's <action_block> other than
normal statements.

Each 'IF' condition should have a separate 'END IF' statement which marks
the end-of-scope of that particular <action_block>.

The 'IF' statement will consider the nearest 'END IF' statement as an endpoint
for that particular condition.

Syntax
IF condition1 THEN
-- executes when the boolean expression 1 is true
IF condition 2 THEN
-- executes when the boolean expression 2 is true
statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
statements;
END IF;
Ex.:-
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/

Output
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
4.2.1(B) CASE Statement

A CASE statement is similar to IF-THEN-ELSIF statement that selects one


alternative based on the condition from the available options.

 CASE statement uses "selector" rather than a Boolean expression to


choose the sequence.
 The value of the expression in the CASE statement will be treated as a
selector.
 The expression could be of any type (arithmetic, variables, etc.)
 Each alternative is assigned with a certain pre-defined value (selector),
and the alternative with selector value that matches the conditional
expression value will get executed.
 Unlike IF-THEN-ELSIF, the CASE statement can also be used in SQL
statements.
 ELSE block in CASE statement holds the sequence that needs to be
executed when none of the alternatives got selected.

1. Simple case

Syntax:

CASE selector
WHEN <valuel> THEN action_blockl;
WHEN <value2> THEN action_block2;
WHEN <value3> THEN action_block3;
ELSE action_block_default;
END CASE;

 In the above syntax, the expression will return a value that could be of
any type (variable, number, etc.).
 Each 'WHEN' clause is treated as an alternatives which have <value>
and <action_block>.
 The 'WHEN' clause which matches the value as that of the expression
will be selected, and the corresponding <action_block> will be executed.
 'ELSE' block is optional which hold the <action_block_default> that
needs to be executed when none of the alternatives match the
expression value.
 The 'END' marks the end of the CASE statement, and it is a mandatory
part of the CASE.
Ex:-

DECLARE
a NUMBER :=55;
b NUMBER :=5;
arth_operation VARCHAR2(20) :='MULTIPLY’;
BEGIN
dbms_output.put_line(‘Program started.' );
CASE (arth_operation)
WHEN ‘ADD’ THEN dbms_output.put_line(‘Addition of the numbers are: '|| a+b );
WHEN ‘SUBTRACT' THEN dbms_output.put_line(‘Subtraction of the numbers are: '||a-b );
WHEN ‘MULTIPLY' THEN dbms_output.put_line(‘Multiplication of the numbers are: '|| a*b
);
WHEN ‘DIVIDE' THEN dbms_output.put_line(‘Division of the numbers are:'|| a/b);
ELSE dbms_output.put_line(‘No operation action defined. Invalid operation');
END CASE;
dbms_output.put_line(‘Program completed.' );
END;
/

Output

Program started.
Multiplication of the numbers are: 275
Program completed.

2. SEARCHED CASE Statement


The SEARCHED CASE statement is similar to the CASE statement, rather
than using the selector to select the alternative, SEARCHED CASE will
directly have the expression defined in the WHEN clause.

 The first WHEN clause that satisfies the condition will be executed, and
the controller will skip the remaining alternatives.

Syntax:

CASE
WHEN <expression1> THEN action_blockl;
WHEN <expression2> THEN action_block2;
WHEN <expression3> THEN action_block3;
ELSE action_block_default;
END CASE;

 In the above syntax, each WHEN clause has the separate <expression>
and <action_block>.
 The WHEN clause for which the expression returns TRUE will be
executed.
 'ELSE' block is optional which hold the <action_block_default> that
needs to be executed when none of the alternatives satisfies.
 The 'END' marks the end of the CASE statement and, it is a mandatory
part of CASE.

Example 1: Arithmetic Calculation using Searched Case

In this example, we are going to do arithmetic calculation between two


numbers 55 and 5.

DECLARE a NUMBER :=55;


b NUMBER :=5;
arth_operation VARCHAR2(20) :='DIVIDE';
BEGIN
dbms_output.put_line(‘Program started.' );
CASE
WHEN arth_operation = 'ADD'
THEN dbms_output.put_line(‘Addition of the numbers are: '||a+b );
WHEN arth_operation = ‘SUBTRACT'
THEN dbms_output.put_line(‘Subtraction of the numbers are: '|| a-b);
WHEN arth_operation = ‘MULTIPLY’
THEN dbms_output.put_line(‘Multiplication of the numbers are: '|| a*b );
WHEN arth_operation = ’DIVIDE'
THEN dbms_output.put_line(‘Division of the numbers are: '|| a/b ):
ELSE dbms_output.put_line(‘No operation action defined. Invalid operation');
END CASE;
dbms_output.put_line(‘Program completed.' );
END;
/
Program started.
Division of the numbers are: 11
Program completed.
4.2.2 Iterative Control

You might also like