DMS Notes
DMS Notes
Data: - user input to the system. User give input in any format such as Text, image, alpha numeric etc.
using input devices.
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
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.
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.
2. Data Inconsistency
4 .Data dependence
7. Integrity problems
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
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 .
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.
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. 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.
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.
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)
• 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
Changes Frequently.
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 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
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: 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.
These users also handles the system where data storage is complex. i. e. data can be in the form of graphics,
audio, video etc.
DBA is a person who has central control over the data as well as the application program.
1. Schema Definition. 2. Storage structure and Access-method definition 3. Schema and physical-organization
modification.
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
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.
c) Easy to access.
Roll_no
Staff_Id Staff_Name S_Name
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.
Advantages:-
a) Simple b) user Friendly c) Flexible.
These attributes decides the categories of the information (data) which makes the record. Record is collection of
related information (data).
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:-
ER model is a conceptual data model that views the real world as entities and relationships.
Ex.-persons, things, organizations etc. Persons like staff, students, employees, customers.etc
Relationship: - it can be defined as an association among several entities.it exactly tells how one entity is related
to another entity.
One to One,
One to Many,
The pictorial representation of data using different conventions which state that how data are related to each
other is known as Entity relationship diagrams.
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.
Ex.
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.
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.
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.
To maintain integrity.
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
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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
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
1 Programming C
2 Programming VB
3 Scripting PHP
4 Scripting HTML
2.5. Second Normal Form (2NF)
TEACHER table
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.
Super key in the table above:1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on
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:-
EMPLOYEE_ZIP table:
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 SQL is a database language, it is used for database creation, deletion, fetching rows, and modifying
rows, etc.
All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL Server use SQL as standard
database language.
Rules:
- 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.
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
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;
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.
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.
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
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.
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:
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.
The DEFAULT constraint provides a default value to a column when there is no value provided while
inserting a record into a table.
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.
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.
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)
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.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
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
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
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:-
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:-
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.
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.
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:
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
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.
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.
• Arithmetic operators
• Comparison operators
• Logical operators
• Bitwise Operators. Compound Operators Set Operators.
- (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
= 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.
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.
| 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.
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;
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.
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;
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.
There are two wildcards often used in conjunction with the LIKE operator:
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:
WHERE CustomerName LIKE Finds any values that ends with "a"
'%a'
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
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.
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)
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
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:-LENGTH( string1 )
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 )
Syntax:-ABS( number )
Syntax:-POWER( m, n )
Syntax:-SQRT( n )
Syntax:-CEIL( number )
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 )
Syntax:-LOG( m, n )
Ex:- MOD( m, n )
Ex:-SIGN( number )
syntax:-SIN( n )
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 )
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 )
4 Row WHERE clause select the rows before On other hand Having
selection grouping of result. clause selects the rows
after grouping.
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.
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.
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.
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.
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.
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
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’);
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:
Where
Initial_value should be greater than or equal to minimum value and less than equal to maximum
value.
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:
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
2. Composite Index
This index created on a multiple columns of a table.
Syntax
Syntax
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
Dropping Index:-
To remove index from database object you can use the drop index command
Syntax:-
Drop index indexname;
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;
We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.
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:
2. StudentCourse
1. Inner Join:-
Output:
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
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output
5.Self join:
Ex:-
Outpout
Chapter 4 PL/SQL Programming
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.
Features of PL/SQL
PL/SQL has the following features −
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.
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
DBMS_OUTPUT.PUT_LINE ();
This statement is used to print the message or values.
Ex:-
declare
i number;
begin
i:=1;
i:=i+1;
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.
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
Numeric Data type stores real nu,bers,floating point numbers,zero and infinity
DateTime stores date and time values with fractional precision of seconds.
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
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.
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.
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.
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 –
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.
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
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.
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
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.
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.