Professional Documents
Culture Documents
DMS 22319 Notes
DMS 22319 Notes
MANAGEMENT
SYSTEMS
(22319)
Department of Computer Engineering
State the importance of DBMS over file processing in the given situation.
Describe the overall structure of the given DBMS
Identify the relevant database model in the given situation.
Draw the E-R diagram of the given database and identify relationship between the
entities.
1.1 Data:
Data is nothing but the information which is having implicit meaning.
Data is a set of values of qualitative or quantitative variables about one or more objects.
It is facts and statistics collected together for reference or analysis.
1.2 Database:
A database is a collection of information that is organized so that it can be easily
accessed, managed and updated.
Manufacturing It is used for the management of supply chain and for tracking
production of items. Inventories status in warehouses.
Example: Information of student like roll number, class, division, name, etc. is
repeated in student details file system and library details file system.
Duplication of data results in data redundancy.
Data redundancy increases the cost of storing and retrieving the data.
If some update is done on these database and if the values of these common fields are
not matching for some records in both files, then it results in inconsistent data.
Logical data independence: It is the capacity to change the logical schema (conceptual
schema) without having to change external schema or application program.
Naïve Users: They are unsophisticated user to interact with system by using pre-
developed application program.
Application Programmers: They are computer professional who interact with the
system through Data Manipulation Language calls. DBMS calls which are embedded
in a program written in a host system language.
Sophisticated Users: They interact with system without writing programs instead
they form their request in a database query language.
Specialized Users: They are also sophisticated users who writes specialized databases
applications that do not fit in traditional data processing unit.
Query Processor:
As query is very much necessary to find out only the data user need from tons of data
of the database, query processor is very important to process these query requests.
Query processors come with the following components,
1. DDL Interpreter: It interprets the DDL statements and records the definitions in
data dictionary.
2. DML Compiler: It translates the DML statements in a query language into an
evaluation plan consisting of low-level instructions that the query evaluation
understands. It also performs query optimization which actually picks up the lowest
cost evaluation plan from various alternatives.
3. Query Evaluation Engine: It executes the low level instruction compiled by the
DML compiler.
Storage Manager:
A storage manager is a program module which is responsible for storing, retrieving and
updating data in the database.
Following are the components of the storage manager;
1. Authorization and Integrity Manager: It tests the integrity constraints and checks
the authorization of users to access data.
2. Transaction Manager: It ensures that no kind of change will be brought to the
database until a transaction has been completed totally.
3. File Manager: It manages the allocation of space on disk storage and the data
structures used to represent information stored on disk.
4. Buffer Manager: It decides which data is in need to be cached in main memory
and then fetch it up in main memory. This is very important as it defines the speed
in which the database can be used.
o A data model helps design the database at the conceptual, physical and logical
levels.
o Data Model structure helps to define the relational tables, primary and foreign
keys and stored procedures.
o It provides a clear picture of the base data and can be used by database
developers to create a physical database.
o It is also helpful to identify missing and redundant data.
o Though the initial creation of data model is labor and time consuming, in the
long run, it makes your IT infrastructure upgrade and maintenance cheaper and
faster.
Advantages:
A user can retrieve data very quickly due to the presence of explicit links between the
table structures.
The referential integrity is built in and automatically enforced due to which a record in
a child table must be linked to an existing record in a parent table, along with that if a
record deleted in the parent table then that will cause all associated records in the child
table to be deleted as well.
Disadvantages:
When a user needs to store a record in a child table that is currently unrelated to any
record in a parent table, it gets difficulty in recording and user must record an additional
entry in the parent table.
This type of database cannot support complex relationships, and there is also a problem
of redundancy, which can result in producing inaccurate information due to the
inconsistent recording of data at various sites.
from one record to another by following the relationships in which the record
participates.
Records can also be located by supplying key values.
The following diagram depicts a network model. An agent represents several clients
and manages several entertainers. Each client schedules any number of engagements
and makes payments to the agent for his or her services. Each entertainer performs
several engagements and may play a variety of musical styles.
Advantages:
Fast data access.
It also allows users to create queries that are more complex than those they created
using a hierarchical database. So, a variety of queries can be run over this model.
Disadvantages:
A user must be very familiar with the structure of the database to work through the set
structures.
Updating inside this database is a tedious task. One cannot change a set structure
without affecting the application programs that use this structure to navigate through
the data. If you change a set structure, you must also modify all references made from
within the application program to that structure.
Advantages:
Improved data sharing: Data is retained by usual business process and manipulated
on a server is available for designated users (clients) over an authorized access.
Integration of services: Every client is given the opportunity to access corporate
information via desktop interface eliminating the necessity to log into a terminal node
or process.
Easy maintenance: In distributed model, responsibilities are dispersed among
independent computers integrated across a network. Therefore, it is easy to replace,
repair, upgrade and relocate a server while clients remain unaffected.
Security: Servers have better control access and resources to ensure that only
authorized clients can access or manipulate data and server updates are administered
effectively.
Disadvantages:
Overloaded Servers: When there are frequent simultaneous client requests, server
services get overloaded forming traffic congestion.
Impact of Centralized Architecture: Since, it is centralized, if the critical server fails,
client’s requests are not accomplished. Therefore, client-servers lacks the robustness of
the good network.
In two-tier architecture, the Database system is present at the server machine and the
DBMS application is present at the client machine, these two machines are connected
with each other through a reliable network as shown in the above diagram.
Whenever client machine makes a request to access the database present at server using
a query language like SQL, the server perform the request on the database and returns
the result back to the client.
The application connection interface such as JDBC, ODBC are used for the interaction
between server and client.
In three-tier architecture, another layer is present between the client machine and server
machine.
In this architecture, the client application doesn’t communicate directly with the
database systems present at the server machine, rather the client application
communicates with server application and the server application internally
communicates with the database system present at the server.
Entity:
An entity can be a real-world object, either animate or inanimate, that can be easily
identifiable.
For example, in a school database, students, teachers, classes, and courses offered can
be considered as entities.
All these entities have some attributes or properties that give them their identity.
An entity set is a collection of similar types of entities. An entity set may contain
entities with attribute sharing similar values.
For example, a Students set may contain all the students of a school; likewise a
Teachers set may contain all the teachers of a school from all faculties.
Strong Entity:
A strong entity is not dependent of any other entity in the schema. A strong entity will
always have a primary key.
Weak Entity:
A weak entity is an entity that cannot be uniquely identified by its attributes alone;
therefore, it must use a foreign key in conjunction with its attributes to create a primary
key.
For example: a ROOM can only exist in a BUILDING. On the other hand, a TIRE might
be considered as a strong entity because it also can exist without being attached to
a CAR.
Composite attribute − Composite attributes are made of more than one simple
attribute. For example, a student's complete name may have first_name and
last_name.
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.
Relationship:
The association among entities is called a relationship.
For example, an employee works_at a department, a student enrolls in a course. Here,
works_at and enrolls are called relationships.
Relationship Set:
A set of relationships of similar type is called a relationship set.
Like entities, a relationship too can have attributes.
These attributes are called descriptive attributes.
Degree of Relationship:
The number of participating entities in a relationship defines the degree of the
relationship.
o Binary = degree 2
o Ternary = degree 3
o n-ary = degree N
Mapping Cardinalities:
Cardinality defines the number of entities in one entity set, which can be associated
with the number of entities of other set via relationship set.
One-to-one − One entity from entity set A can be associated with at most one entity
of entity set B and vice versa.
One-to-many − One entity from entity set A can be associated with more than one
entities of entity set B however an entity from entity set B, can be associated with at
most one entity.
Many-to-one − More than one entities from entity set A can be associated with at most
one entity of entity set B, however an entity from entity set B can be associated with
more than one entity from entity set A.
Many-to-many − One entity from A can be associated with more than one entity from
B and vice versa.
1.20.2 Attributes:
Attributes are the properties of entities. Attributes are represented by means of ellipses.
Every ellipse represents one attribute and is directly connected to its entity (rectangle).
If the attributes are composite, they are further divided in a tree like structure.
Every node is then connected to its attribute. That is, composite attributes are
represented by ellipses that are connected with an ellipse.
1.20.3 Relationship:
Relationships are represented by diamond-shaped box. Name of the relationship is
written inside the diamond-box. All the entities (rectangles) participating in a
relationship, are connected to it by a line.
Binary Relationship and Cardinality
A relationship where two entities are participating is called a binary relationship.
Cardinality is the number of instance of an entity from a relation that can be associated
with the relation.
One-to-one: When only one instance of an entity is associated with the relationship,
it is marked as '1:1'. The following image reflects that only one instance of each entity
should be associated with the relationship. It depicts one-to-one relationship.
Many-to-one: When more than one instance of entity is associated with the
relationship, it is marked as 'N:1'. The following image reflects that more than one
instance of an entity on the left and only one instance of an entity on the right can be
associated with the relationship. It depicts many-to-one relationship.
Many-to-many: The following image reflects that more than one instance of an entity
on the left and more than one instance of an entity on the right can be associated with
the relationship. It depicts many-to-many relationship.
1.21 Generalization:
As mentioned above, the process of generalizing entities, where the generalized
entities contain the properties of all the generalized entities, is called generalization.
In generalization, a number of entities are brought together into one generalized entity
based on their similar characteristics.
For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.
1.22 Specialization:
Specialization is the opposite of generalization. In specialization, a group of entities is
divided into sub-groups based on their characteristics.
Take a group ‘Person’ for example. A person has name, date of birth, gender, etc.
These properties are common in all persons, human beings. But in a company, persons
can be identified as employee, employer, customer, or vendor, based on what role they
play in the company.
1.23 Inheritance
We use all the above features of ER-Model in order to create classes of objects in
object-oriented programming.
The details of entities are generally hidden from the user; this process known
as abstraction.
Inheritance is an important feature of Generalization and Specialization.
It allows lower-level entities to inherit the attributes of higher-level entities.
For example, the attributes of a Person class such as name, age, and gender can be
inherited by lower-level entities such as Student or Teacher.
Explain the concept of RDBMS also appropriateness for the given problem.
Design normalized database structure in the given problem.
Design SQL queries to create relational database and apply in the given data
constraints.
Identify the operators for queries implementation of the given problem.
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.4 Constraints
Every relation has some conditions that must hold for it to be a valid relation.
These conditions are called Relational Integrity Constraints.
There are three main integrity constraints:
Prof. Hitesh Mhatre 2-3
Database Management Systems – 22319 CO-3I
o Key constraints
o Domain constraints
o Referential integrity constraints
2.5 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.
o 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.
Each attribute must contain only a single value from its pre-defined domain.
We see here in Student_Project relation that the prime key attributes are Stu_ID and
Proj_ID.
According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be
dependent upon both and not on any of the prime key attribute individually.
But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be
identified by Proj_ID independently.
This is called partial dependency, which is not allowed in Second Normal Form.
We broke the relation in two as depicted in the above picture. So there exists no partial
dependency.
We find that in the above Student_Detail relation, Stu_ID is the key and only prime
key attribute.
We find that City can be identified by Stu_ID as well as Zip itself.
Neither Zip is a super key nor is City a prime attribute.
Additionally, Stu_ID → Zip → City, so there exists transitive dependency.
To bring this relation into third normal form, we break the relation into two relations
as follows −
SQL Data Types define the type of value that can be stored in a table column.
SQL data types can be broadly divided into following categories.
1. Numeric data types such as int, tinyint, bigint, float, real etc.
2. Date and Time data types such as Date, Time, Datetime etc.
3. Character and String data types such as char, varchar, text etc.
4. Unicode character string data types, for example nchar, nvarchar, ntext etc.
5. Binary data types such as binary, varbinary etc.
6. Miscellaneous data types – clob, blob, xml, cursor, table etc.
Datatype From To
bit 0 1
tinyint 0 255
Datatype Description
Datatype Description
Note that all the above data types are for character stream, they should not be used with
unicode data.
Prof. Hitesh Mhatre 2-9
Database Management Systems – 22319 CO-3I
Datatype Description
Note that above data types are not supported in MySQL database.
Datatype Description
IMAGE Variable length storage with maximum size of 2GB binary data
Datatype Description
The purpose of DQL Command is to get some schema relation based on the query
passed to it.
2.11.2 ALTER
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
2.11.3 DROP
The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!
2.11.4 TRUNCATE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
Syntax
TRUNCATE TABLE table_name;
2.11.5 DESC
SQL DESC statement use for describe the list of column definitions for specified table.
You can use either DESC or DESCRIBE statement. both are return same result.
DESCRIBE statement to get following information:
o Column Name
o Column allow NULL or NOT NULL
o Datatype of the Column
o With database size precision and If NUMERIC datatype scale.
Syntax
SQL DESCRIBE Table Column use following syntax,
DESC table_name
Example
DESC users_info;
2.11.6 RENAME
RENAME TABLE syntax is used to change the name of a table. Sometimes, we choose
non-meaningful name for the table. So it is required to be changed.
Syntax
RENAME old_table _name TO new_table_name;
Example
RENAME STUDENTS TO ARTISTS;
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).
"Orders" table:
Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it points
to.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table is created:
MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;
MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';
Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the
same order as the columns in the table. The INSERT INTO syntax would be as follows:
Prof. Hitesh Mhatre 2-24
Database Management Systems – 22319 CO-3I
The following SQL statement inserts a new record in the "Customers" table:
INSERT INTO Customers (CustomerName, ContactName,
Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen',
'Skagen 21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically
when a new record is inserted into the table.
The selection from the "Customers" table will now look like this:
2.13.2 DELETE
The DELETE statement is used to delete existing records in a table.
Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) should be deleted.
If you omit the WHERE clause, all records in the table will be deleted!
Below is a selection from the "Customers" table in the sample database:
Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
2.13.2 UPDATE
The UPDATE statement is used to modify the existing records in a table.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the
UPDATE statement. The WHERE clause specifies which record(s) that should be
updated. If you omit the WHERE clause, all records in the table will be updated!
Below is a selection from the "Customers" table in the sample database:
The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will
be updated!
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
2.14.2 SAVEPOINT
SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required
2.14.3 ROLLBACK
This command restores the database to last commited state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK
command to rollback those changes, if they were not commited using the COMMIT
command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
2.14.4 GRANT
You can GRANT and REVOKE privileges on various database objects in SQL Server.
We'll look at how to grant and revoke privileges on tables in SQL Server.
You can grant users various privileges to tables. These permissions can be any
combination of SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, or
ALL.
The syntax for granting privileges on a table in SQL Server is:
GRANT privileges ON object TO user;
For example, if you wanted to grant SELECT, INSERT, UPDATE, and DELETE
privileges on a table called employees to a user name smithj, you would run the
following GRANT statement:
GRANT SELECT, INSERT, UPDATE, DELETE ON employees TO smithj;
You can also use the ALL keyword to indicate that you wish to grant the ANSI-92
permissions (ie: SELECT, INSERT, UPDATE, DELETE, and REFERENCES) to a
user named smithj.
For example:
GRANT ALL ON employees TO smithj;
If you wanted to grant only SELECT access on the employees table to all users, you
could grant the privileges to the public role. For example:
GRANT SELECT ON employees TO public;
2.14.5 REVOKE
Once you have granted privileges, you may need to revoke some or all of these
privileges. To do this, you can run a revoke command. You can revoke any combination
of SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, or ALL.
The syntax for revoking privileges on a table in SQL Server is:
REVOKE privileges ON object FROM user;
For example, if you wanted to revoke DELETE privileges on a table called employees
from a user named anderson, you would run the following REVOKE statement:
REVOKE DELETE ON employees FROM anderson;
If you wanted to revoke ALL ANSI-92 permissions (ie: SELECT, INSERT, UPDATE,
DELETE, and REFERENCES) on a table for a user named anderson, you could use the
ALL keyword as follows:
REVOKE ALL ON employees FROM anderson;
If you had granted SELECT privileges to the public role (ie: all users) on the employees
table and you wanted to revoke these privileges, you could run the following REVOKE
statement:
REVOKE SELECT ON employees FROM public;
Example
The following SQL statement selects the "CustomerName" and "City" columns from
the "Customers" table:
SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
SELECT * FROM Customers;
Example
The following SQL statement selects all the customers from the country "Mexico", in
the "Customers" table:
SELECT * FROM Customers
WHERE Country='Mexico';
Subtraction (-):
It is use to perform subtraction operation on the data items, items include either single column
or multiple columns.
SELECT employee_id, employee_name, salary, salary - 100
AS "salary - 100" FROM subtraction;
Multiplication (*):
It is use to perform multiplication of data items.
SELECT employee_id, employee_name, salary, salary * 100
AS "salary * 100" FROM addition;
Modulus ( % ):
It is use to get remainder when one data is divided by another.
SELECT employee_id, employee_name, salary, salary % 25000
AS "salary % 25000" FROM addition;
2.16.2 Comparison
SELECT * FROM Products
WHERE Price = 18;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
The table below shows the complete "Customers" table from the sample database:
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany"
OR "Spain":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany" and NOT "USA":
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France"
or "UK":
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the
suppliers:
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
2.16.5 Between
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.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Below is a selection from the "Products" table in the sample database:
BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
The following SQL statement selects all products with a ProductName BETWEEN
Carnarvon Tigers and Chef Anton's Cajun Seasoning:
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;
The table below shows the complete "Customers" table from the sample database: 91 entries
The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in
any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:
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:
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":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does NOT
start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
2. CHAR_LENGTH(str)
Returns the length of the string str measured in characters. A multi-byte character
counts as a single character. This means that for a string containing five two-byte
characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
SELECT CHAR_LENGTH("Hello");
CHAR_LENGTH("Hello")
--------------------------
5
3. CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more
arguments. If all arguments are non-binary strings, the result is a non-binary string. If
the arguments include any binary strings, the result is a binary string. A numeric
argument is converted to its equivalent binary string form; if you want to avoid that,
you can use an explicit type cast, as in this example −
4. LCASE(str)
LCASE() is a synonym for LOWER().
5. LEFT(str,len)
Returns the leftmost len characters from the string str, or NULL if any argument is
NULL.
SELECT LEFT('Engineering', 5);
LEFT('Engineering', 5)
---------------------------------------------------------
Engin
6. LENGTH(str)
Returns the length of the string str, measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters,
LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
SELECT LENGTH('text');
LENGTH('Hello')
---------------------------------------------------------
5
7. LOWER(str)
Returns the string str with all characters changed to lowercase according to the current
character set mapping.
SELECT LOWER('QUADRATICALLY');
LOWER('QUADRATICALLY')
---------------------------------------------------------
quadratically
8. LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
SELECT LPAD('hi',4,'??');
LPAD('hi',4,'??')
---------------------------------------------------------
??hi
9. LTRIM(str)
Returns the string str with leading space characters removed.
SELECT LTRIM(' diploma');
LTRIM(' diploma’)
---------------------------------------------------------
diploma
10. REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string
to_str. REPLACE() performs a case-sensitive match when searching for from_str.
SELECT REPLACE('www.mysql.com', 'w', 'Ww');
REPLACE('www.mysql.com', 'w', 'Ww')
---------------------------------------------------------
WwWwWw.mysql.com
11. REVERSE(str)
Returns the string str with the order of the characters reversed.
SELECT REVERSE('Hello');
REVERSE(‘Hello’)
---------------------------------------------------------
olleH
12. RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if any argument is
NULL.
SELECT RIGHT('Engineering', 4);
RIGHT('Engineering', 4)
---------------------------------------------------------
ring
13. RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters.
If str is longer than len, the return value is shortened to len characters.
SELECT RPAD('hi',5,'?');
RPAD('hi',5,'?')
---------------------------------------------------------
hi???
14. RTRIM(str)
Returns the string str with trailing space characters removed.
SELECT SUBSTRING('Quadratically',5,6);
SUBSTRING('Quadratically',5,6)
---------------------------------------------------------
ratica
18. UCASE(str)
UCASE() is a synonym for UPPER().
19. UPPER(str)
Returns the string str with all characters changed to uppercase according to the current
character set mapping.
SELECT UPPER('Database-Management-System');
UPPER('Database-Management-System')
---------------------------------------------------------
DATABASE-MANAGEMENT-SYSTEM
2. MOD(X,Y)
The variable X is divided by Y and their remainder is returned. For example
SELECT MOD(9,5);
This returns 4.
3. SIGN(X)
This method returns 1 if X is positive, -1 if it is negative and 0 if the value of X is 0.
For example
SELECT SIGN(10);
This returns 1.
4. FLOOR(X)
This returns the largest integer value that is either less than X or equal to it. For example
SELECT FLOOR(5.7);
This returns 5.
5. CEIL(X)
This returns the smallest integer value that is either more than X or equal to it. For
example
SELECT CEIL(5.7);
This returns 6.
6. POWER(X,Y)
This function returns the value of x raised to the power of Y. For example
SELECT POWER(2,5);
This returns 32.
7. ROUND(X)
This function returns the value of X rounded off to the whole integer that is nearest to
it. For example
SELECT ROUND(5.7);
This returns 6.
8. SQRT(X)
This function returns the square root of X. For example
SELECT SQRT(9);
This returns 3.
9. ASIN(X)
This function accepts a Sin value as the input and returns the angle in radians. For
example
SELECT ASIN(0);
This returns 0.
10. ACOS(X)
This function accepts a Cos value as the input and returns the angle in radians. For
example
SELECT ACOS(1);
This returns 0.
11. ATAN(X)
This function accepts a Tan value as the input and returns the angle in radians. For
example
SELECT ATAN(0);
This returns 0.
12. SIN(X)
This function accepts an angle in radians as its parameter and returns its Sine value. For
example
SELECT SIN(0);
This returns 0.
13. COS(X)
This function accepts an angle in radians as its parameter and returns its Cosine value.
For example
SELECT COS(0);
This returns 1.
14. TAN(X)
This function accepts an angle in radians as its parameter and returns its Tan value. For
example
SELECT TAN(0);
This returns 0.
SELECT CURDATE();
CURDATE()
--------------------------------------------------------
1997-12-15
SELECT CURDATE() + 0;
CURDATE() + 0
--------------------------------------------------------
19971215
2. CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or in a numeric context. The value is expressed
in the current time zone.
SELECT CURTIME();
CURTIME()
---------------------------------------------------------
23:50:26
SELECT CURTIME() + 0;
CURTIME() + 0
---------------------------------------------------------
235026
3. DATE(expr)
Extracts the date part of the date or date time expression expr.
SELECT DATE('2003-12-31 01:02:03');
DATE('2003-12-31 01:02:03')
---------------------------------------------------------
2003-12-31
4. DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the
other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts
of the values are used in the calculation.
5. DATE_FORMAT(date,format)
This command formats the date value as per the format string.
The following specifiers may be used in the format string. The '%' character is required
before the format specifier characters.
6. DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function.
7. DAYNAME(date)
Returns the name of the weekday for date.
Prof. Hitesh Mhatre 3-10
Database Management Systems – 22319 CO-3I
SELECT DAYNAME('1998-02-05');
| DAYNAME('1998-02-05') |
---------------------------------------------------------
| Thursday |
8. DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
SELECT DAYOFMONTH('1998-02-03');
| DAYOFMONTH('1998-02-03') |
---------------------------------------------------------
|3 |
9. DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index
values correspond to the ODBC standard.
SELECT DAYOFWEEK('1998-02-03');
|DAYOFWEEK('1998-02-03') |
---------------------------------------------------------
|3 |
10. DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
SELECT DAYOFYEAR('1998-02-03');
| DAYOFYEAR('1998-02-03') |
---------------------------------------------------------
| 34 |
11. HOUR(time)
Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values greater
than 23.
SELECT HOUR('10:05:03');
| HOUR('10:05:03') |
---------------------------------------------------------
| 10 |
12. LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the month.
Returns NULL if the argument is invalid.
SELECT LAST_DAY('2003-02-05');
| LAST_DAY('2003-02-05') |
---------------------------------------------------------
| 2003-02-28 |
13. MINUTE(time)
Returns the minute for time, in the range 0 to 59.
SELECT MINUTE('98-02-03 10:05:03');
---------------------------------------------------------
| MINUTE('98-02-03 10:05:03') |
---------------------------------------------------------
|5 |
14. MONTH(date)
Returns the month for date, in the range 0 to 12.
SELECT MONTH('1998-02-03')
| MONTH('1998-02-03') |
---------------------------------------------------------
|2 |
15. MONTHNAME(date)
Returns the full name of the month for a date.
SELECT MONTHNAME('1998-02-05');
| MONTHNAME('1998-02-05') |
---------------------------------------------------------
| February |
16. NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. This value is expressed in the current time zone.
SELECT NOW();
| NOW() |
---------------------------------------------------------
| 1997-12-15 23:50:26 |
17. SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in
a numeric context.
SELECT SYSDATE();
| SYSDATE() |
---------------------------------------------------------
| 2006-04-12 13:47:44 |
18. WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).
SELECT WEEKDAY('1998-02-03 22:23:00');
| WEEKDAY('1998-02-03 22:23:00') |
---------------------------------------------------------
|1 |
19. WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR()
is a compatibility function that is equivalent to WEEK(date,3).
SELECT WEEKOFYEAR('1998-02-20');
| WEEKOFYEAR('1998-02-20') |
---------------------------------------------------------
|8 |
20. YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.
SELECT YEAR('98-02-03');
| YEAR('98-02-03') |
---------------------------------------------------------
| 1998 |
3.2 Aggregate
The SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
COUNT() Example
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Price)
FROM Products;
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MIN() Example
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MAX() Example
The following SQL statement finds the price of the most expensive product:
SELECT MAX(Price) AS LargestPrice
FROM Products;
3.3 Group By
The GROUP BY statement groups’ rows that have the same values into summary rows,
like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the sample database:
The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
3.4 Having
The HAVING clause was added to SQL because the WHERE keyword could not be
used with aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the sample database:
3.5 Order By
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Below is a selection from the "Customers" table in the sample database:
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country;
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:
1. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Demo Database
2. LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match.
3. RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched
records from the left table (table1). The result is NULL from the left side, when there is no
match.
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether
the other table matches or not. So, if there are rows in "Customers" that do not have matches
in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those
rows will be listed as well.
3.7 Sub-queries:
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
o Subqueries must be enclosed within parentheses.
o A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
o An ORDER BY command cannot be used in a subquery, although the main
query can use an ORDER BY. The GROUP BY command can be used to
perform the same function as the ORDER BY in a subquery.
o Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
o The SELECT list cannot include any references to values that evaluate to a
BLOB, ARRAY, CLOB, or NCLOB.
o A subquery cannot be immediately enclosed in a set function.
o The BETWEEN operator cannot be used with a subquery. However, the
BETWEEN operator can be used within the subquery.
Example
Consider the CUSTOMERS table having the following records −
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
3.8 Views:
3.8.1 CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the 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.
The following SQL creates a view that selects every product in the "Products" table with a
price higher than the average price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
We can query the view above as follows:
SELECT * FROM [Products Above Average Price];
3.9 Sequences:
3.9.1 Creating SEQUENCES
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some
database systems to produce unique values on demand.
A sequence is a user defined schema bound object that generates a sequence of numeric
values.
Sequences are frequently used in many databases because many applications require
each row in a table to contain a unique value and sequences provides an easy way to
generate them.
The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
sequence_name: 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.
Example
Following is the sequence query creating sequence in ascending order.
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.
CREATE SEQUENCE sequence_2
start with 100
increment by -1
minvalue 1
maxvalue 100
cycle;
Above query will create a sequence named sequence_2.Sequence will start from 100 and
should be less than or equal to maximum value and will be incremented by -1 having minimum
value 1.
Example to use sequence: create a table named students with columns as id and name
CREATE TABLE students
(
ID number(10),
NAME char(20)
);
3.10 Indexes:
Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. Simply put, an index is a pointer to data in a table. An index in a database
is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic,
you first refer to the index, which lists all the topics alphabetically and are then referred
to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down
data input, with the UPDATE and the INSERT statements. Indexes can be created or
dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate
whether the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as
follows.
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index
does not allow any duplicate values to be inserted into the table. The basic syntax is as follows.
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
composite index would be the best choice.
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an
object is created. Indexes are automatically created for primary key constraints and unique
constraints.
Write simple PL/SQL code using control structure and handle various exceptions in
given situation.
Create cursor for retrieving multiple records in the given situation.
Create and execute stored procedures and functions in the given situation.
Create and apply database trigger using PL/SQL in given situation.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are
different sections of PL/SQL blocks.
1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section order.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is
the section in which the declaration of variables, cursors, exceptions, subprograms,
pragma instructions and collections that are needed in the block will be declared. Below
are few more characteristics of this part.
o This particular section is optional and can be skipped if no declarations are
needed.
o This should be the first section in a PL/SQL block, if present.
o This section starts with the keyword 'DECLARE' for triggers and anonymous
block. For other subprograms, this keyword will not be present. Instead, the part
after the subprogram name definition marks the declaration section.
o This section should always be followed by execution section.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is
written inside it. Since the PL/SQL expects the executable statements from this block
this cannot be an empty block, i.e., it should have at least one valid executable code line
in it. Below are few more characteristics of this part.
o This can contain both PL/SQL code and SQL code.
o This can contain one or many blocks inside it as a nested block.
o This section starts with the keyword 'BEGIN'.
o This section should be followed either by 'END' or Exception-Handling section
(if present)
Exception-Handling Section:
The exception is unavoidable in the program which occurs at run-time and to handle
this Oracle has provided an Exception-handling section in blocks. This section can also
contain PL/SQL statements. This is an optional section of the PL/SQL blocks.
o This is the section where the exception raised in the execution block is handled.
o This section is the last part of the PL/SQL block.
o Control from this section can never return to the execution block.
o This section starts with the keyword 'EXCEPTION'.
o This section should always be followed by the keyword 'END'.
o The Keyword 'END' marks the end of PL/SQL block.
Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
Composite
3 Data items that have internal components that can be accessed individually. For
example, collections and records.
Reference
4
Pointers to other data items.
Numeric
1
Numeric values on which arithmetic operations are performed.
Character
2
Alphanumeric values that represent single characters or strings of characters.
Boolean
3
Logical values on which logical operations are performed.
Datetime
4
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.
PLS_INTEGER
1
Signed integer in range -2,147,483,648 to 2,147,483,647, represented in 32 bits
BINARY_INTEGER
2
Signed integer in range -2,147,483,648 to 2,147,483,647, represented in 32 bits
BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but
not including) 1.0E126. A NUMBER variable can also represent 0
DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits
DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits
NUMERIC(pre, scale)
8
Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
9
ANSI specific floating-point type with maximum precision of 126 binary digits
FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits
INT
11
ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
CHAR
1
Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes
RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes
NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes
LONG
6
Variable-length character string with maximum size of 32,760 bytes
LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL
ROWID
8
Physical row identifier, the address of a row in an ordinary table
UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)
MONTH 01 to 12 0 to 11
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
NULLs in PL/SQL
PL/SQL NULL values represent missing or unknown data and they are not an integer,
a character, or any other specific data type. Note that NULL is not the same as an empty
data string or the null character value '\0'. A null can be assigned but it cannot be equated
with anything, including itself.
END;
/
When the above code is executed, it produces the following result −
Customer Ramesh from Ahmedabad earns 2000
PL/SQL procedure completed successfully
IF - THEN statement
The IF statement associates a condition with a sequence of statements enclosed by the
1
keywords THEN and END IF. If the condition is true, the statements get executed and if
the condition is false or NULL then the IF statement does nothing.
IF-THEN-ELSE statement
IF statement adds the keyword ELSE followed by an alternative sequence of statement. If
2
the condition is false or NULL, then only the alternative sequence of statements get
executed. It ensures that either of the sequence of statements is executed.
IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.
Case statement
Like the IF statement, the CASE statement selects one sequence of statements to execute.
4 However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression whose value is used to select one of
several alternatives.
nested IF-THEN-ELSE
6 You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-
THEN-ELSIF statement(s).
4.3.1.1 IF Statement
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if
the condition is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN
S;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
4.3.1.2 IF-THEN_ELSE
A sequence of IF-THEN statements can be followed by an optional sequence of ELSE
statements, which execute when the condition is FALSE.
Syntax for the IF-THEN-ELSE statement is −
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements,
when the test condition is TRUE, the statement S1 is executed and S2 is skipped; when the test
condition is FALSE, then S1 is bypassed and statement S2 is executed.
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
4.3.1.3 IF-THEN-ELSEIF:
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An
IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The
ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
o It's ELSEIF, not ELSEIF.
o An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSEIF's.
o An IF-THEN statement can have zero to many ELSEIF's and they must come
before the ELSE.
o Once an ELSEIF succeeds, none of the remaining ELSEIF's or ELSE's will be
tested.
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Example:
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
None of the values is matching
Exact value of a is: 100
PL/SQL procedure successfully completed.
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent
PL/SQL procedure successfully completed.
4.3.2 LOOPS
There may be a situation when you need to execute a block of code several number of
times.
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages
PL/SQL provides the following types of loop to handle the looping requirements. Click
the following links to check their detail
value of a: 18
value of a: 19
value of a: 20
PL/SQL procedure successfully completed.
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
PL/SQL procedure successfully completed.
The above program displays the name and address of a customer whose ID is given. Since there
is no customer with ID value 8 in our database, the program raises the run-time exception
NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE. Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-
defined exception. In the next section, we will give you an example on raising a user-
defined exception. You can raise the Oracle standard exceptions in a similar way.
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
PL/SQL procedure successfully completed.
Oracle
Exception SQLCODE Description
Error
4.5 Cursors
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors
o Implicit cursors
o Explicit cursors
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and
%ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT
and %BULK_EXCEPTIONS, designed for use with the FORALL statement. The
following table provides the description of the most used attributes −
Example
We will be using the CUSTOMERS table.
Select * from customers;
The following program will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.
4.6 Procedures
A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
A subprogram can be created −
o At the schema level
o Inside a package
o Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the
CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the
database and can be deleted with the DROP PROCEDURE or DROP FUNCTION
statement.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on
the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a
1 value. You can pass a constant, literal, initialized variable, or expression as an IN
parameter. You can also initialize it to a default value; however, in that case, it is omitted
from the subprogram call. It is the default mode of parameter passing. Parameters are
passed by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an
2
OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.
3
The actual parameter corresponding to an IN OUT formal parameter must be a variable,
not a constant or an expression. Formal parameter must be assigned a value. Actual
parameter is passed by value.
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23
PL/SQL procedure successfully completed.
4.7 Functions
4.7.1 Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
Example
The following example illustrates how to create and call a standalone function. This function
returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table
Select * from customers;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
To call a function, you simply need to pass the required parameters along with the
function name and if the function returns a value, then you can store the returned value.
Following program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
PL/SQL procedure successfully completed.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' ||
factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
PL/SQL procedure successfully completed.
4.8 Triggers
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
o Triggers can be defined on the table, view, schema, or database with which the
event is associated.
Example
To start with, we will be using the CUSTOMERS table
Select * from customers;
The following program creates a row-level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS
table. This trigger will display the salary difference between the old values and new
values
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
Provide security to the given database by assigning various privileges to the user.
Create and manage the given database users.
Explain the importance of transaction in the given situation.
Explain advantages of database backup and recovery in the given situation.
o Data corruption and/or loss caused by the entry of invalid data or commands,
mistakes in database or system administration processes, sabotage/criminal
damage etc.
Privileges
Two types of privileges are important relating to database security within the database
environment: system privileges and object privileges.
o System privileges allow a user to perform administrative actions in a database.
o Object privileges allow for the use of certain operations on database objects as
authorized by another user. Examples include: usage, select, insert, update, and
references.
5.2 Transactions
The transaction is a set of logically related operation. It contains a group of tasks.
A transaction is an action or series of actions. It is performed by a single user to perform
operations for accessing the contents of the database.
Example: Suppose an employee of bank transfers Rs 800 from X's account to Y's
account. This small transaction contains several low-level tasks:
X's Account
Open_Account(X)
Old_Balance = X.balance
New_Balance = Old_Balance - 800
X.balance = New_Balance
Close_Account(X)
Y's Account
Open_Account(Y)
Old_Balance = Y.balance
New_Balance = Old_Balance + 800
Y.balance = New_Balance
Close_Account(Y)
Operations of Transaction:
Following are the main operations of transaction:
Read(X): Read operation is used to read the value of X from the database and stores it in a
buffer in main memory.
Write(X): Write operation is used to write the value back to the database from the buffer.
Let's take an example to debit transaction from an account which consists of following
operations:
1. R(X);
2. X = X - 500;
3. W(X);
Let's assume the value of X before starting of the transaction is 4000.
The first operation reads X's value from database and stores it in a buffer.
The second operation will decrease the value of X by 500. So buffer will contain 3500.
The third operation will write the buffer's value to the database. So X's final value will
be 3500.
But it may be possible that because of the failure of hardware, software or power, etc.
that transaction may fail before finished all the operations in the set.
For example: If in the above transaction, the debit transaction fails after executing
operation 2 then X's value will remain 4000 in the database which is not acceptable by
the bank.
To solve this problem, we have two important operations:
Commit: It is used to save the work done permanently.
Rollback: It is used to undo the work done.
Atomicity
It states that all operations of the transaction take place at once if not, the transaction is
aborted.
There is no midway, i.e., the transaction cannot occur partially. Each transaction is
treated as one unit and either run to completion or is not executed at all.
Consistency
The integrity constraints are maintained so that the database is consistent before and
after the transaction.
The execution of a transaction will leave a database in either its prior stable state or a
new stable state.
The consistent property of database states that every transaction sees a consistent
database instance.
The transaction is used to transform the database from one consistent state to another
consistent state.
For example: The total amount must be maintained before or after the transaction.
Total before T occurs = 600+300=900
Total after T occurs= 500+400=900
Therefore, the database is consistent. In the case when T1 is completed but T2 fails,
then inconsistency will occur.
Isolation
It shows that the data which is used at the time of execution of a transaction cannot be
used by the second transaction until the first one is completed.
In isolation, if the transaction T1 is being executed and using the data item X, then that
data item can't be accessed by any other transaction T2 until the transaction T1 ends.
The concurrency control subsystem of the DBMS enforced the isolation property.
Durability
The durability property is used to indicate the performance of the database's consistent
state. It states that the transaction made the permanent changes.
They cannot be lost by the erroneous operation of a faulty transaction or by the system
failure. When a transaction is completed, then the database reaches a state known as the
consistent state. That consistent state cannot be lost, even in the event of a system's
failure.
The recovery subsystem of the DBMS has the responsibility of Durability property.
Active state
The active state is the first state of every transaction. In this state, the transaction is
being executed.
For example: Insertion or deletion or updating a record is done here. But all the records
are still not saved to the database.
Partially committed
In the partially committed state, a transaction executes its final operation, but the data
is still not saved to the database.
In the total mark calculation example, a final display of the total marks step is executed
in this state.
Committed
A transaction is said to be in a committed state if it executes all its operations
successfully. In this state, all the effects are now permanently saved on the database
system.
Failed state
If any of the checks made by the database recovery system fails, then the transaction is
said to be in the failed state.
In the example of total mark calculation, if the database is not able to fire a query to
fetch the marks, then the transaction will fail to execute.
Aborted
If any of the checks fail and the transaction has reached a failed state then the database
recovery system will make sure that the database is in its previous consistent state. If
not then it will abort or roll back the transaction to bring the database into a consistent
state.
If the transaction fails in the middle of the transaction then before executing the
transaction, all the executed transactions are rolled back to its consistent state.
After aborting the transaction, the database recovery module will select one of the two
operations:
o Re-start the transaction
o Kill the transaction
o The recovery system reads the logs backwards from the end to the last
checkpoint.
o It maintains two lists, an undo-list and a redo-list.
o If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just
<Tn, Commit>, it puts the transaction in the redo-list.
o If the recovery system sees a log with <Tn, Start> but no commit or abort log
found, it puts the transaction in undo-list.
All the transactions in the undo-list are then undone and their logs are removed. All the
transactions in the redo-list and their previous logs are removed and then redone before
saving their logs.