Unit 3 DBMS
Unit 3 DBMS
UNIT – III
Reference:
✓ SQL and PL/SQL Using ORACLE by Ivan Bayross
✓ Oracle 11g with PL/SQL Approach by Sham Tickoo & Sunil Raina
✓ SQL and PL/SQL for Oracle 11g (BLACK BOOK) by Dr. P.S. Deshpande
Structured Query Language
• SQL (Structured Query Language) is a database sub-language for
querying and modifying relational databases.
• It was developed by IBM Research in the mid 70's and standardized
by ANSI in 1986.
• Relational Model defines two root languages for accessing a
relational database -- Relational Algebra and Relational Calculus.
• Relational Algebra is a low-level, operator-oriented language.
Creating a query in Relational Algebra involves combining relational
operators using algebraic notation.
• Relational Calculus is a high-level, declarative language. Creating a
query in Relational Calculus involves describing what results are
desired.
SQL is a version of Relational Calculus. The basic structure in SQL is
the statement. Semicolons separate multiple SQL statements.
Functions of a DBMS
• Data definition: SQL lets a user define the structure and organization of the
stored data and relationships among the stored data items.
• Data retrieval: SQL allows a user or an application program to retrieve
stored data from the database and use it.
• Data manipulation: SQL allows a user or an application program to update
the database by adding new data, removing old data, and modifying
previously stored data.
• Access control: SQL can be used to restrict a user’s ability to retrieve, add,
and modify data, protecting stored data against unauthorized access.
• Data sharing: SQL is used to coordinate data sharing by concurrent users,
ensuring that they do not interfere with one another.
• Data integrity: SQL defines integrity constraints in the database, protecting
it from corruption due to inconsistent updates or system failures.
• SQL is thus a comprehensive language for controlling and interacting with a
database management system.
Characteristics of SQL
SQL is both an easy-to-understand language and a comprehensive
tool for managing data. Here are some of the major features of SQL
and the market forces that have made it successful:
• Vendor independence
• Relational foundation
• High-level, English-like structure
• Interactive, ad hoc queries
• Programmatic database access
• Multiple views of data
• Complete database language
SQL Common Data Types
• The database users must still enter a value for the new
attribute JOB for each EMPLOYEE tuple.
• This can be done using the UPDATE command.
ALTER TABLE
• Used to remove an attribute from the relation.
Syntax: ALTER TABLE <table name> DROP COLUMN <column name >
Example:
create table branch
(branch_name char(15) not null,branch_city char(30),
assets integer);
CHECK CONSTRAINT
Example:
CREATE TABLE student_mstr( Std_id varchar2(10)
CHECK (Std_id LIKE ‘M%’), name varchar2(20)
CHECK (name =UPPER(name)), address varchar2(30));
DEFAULT VALUE
Example:
CREATE TABLE bank_mstr (name varchar2(20), cust_id
number(10), Curbal number(8,2) DEFAULT 0);
Views
• In some cases, it is not desirable for all users to see the entire
logical model (that is, all the actual relations stored in the
database.)
• If the DBMS needed to scan through all of the data within a table
in order to retrieve the desired information, the process would be
very slow, particularly for tables with millions of rows. To improve
retrieval performance a table can have one or more indexes. Each
index provides a fast "look-up" facility for rows, as an index in a
book allows all references to a topic to be located without reading
every page.
How do Indexes Work?
E.g. Write a SQL query which will return the job description of employees
with the minimum salary in each job description
SELECT job, MIN(salary) from EMP_DATA GROUP BY job;
E.g. Write a SQL query which will return the job description of employees
with total number of employees in each job description
SELECT job, COUNT(*) from EMP_DATA GROUP BY job;
Group By & Having Clause
HAVING clause is used in the Select statement to FILTER the data returned
by the GROUP BY clause.
E.g. Write a SQL query which will return maximum salary of the
employees than 4000.
E.g. Write a SQL query which will return minimum salary of the
employees than 1000.
SELECT Deptno, MIN(salary) from EMP_DATA GROUP BY Deptno
HAVING MAX(salary)>1000;
Group By & Having Clause
•A subquery is a select-from-where
expression that is nested within another query.
• Find all customers who have a loan at the bank but do not
have an account at the bank
select distinct customer_name
from borrower
where customer_name not in (select customer_name
from depositor )
Database Operations
• Insert
• Update
• Delete
INSERT Operation
• Add a new tuple to account
insert into account
values (‘A-9732’, ‘Ghaziabad’,1200)
or equivalently
insert into account (
branch_name, balance, account_number)
values (‘Ghaziabad’, 1200, ‘A-9732’)
• Delete the record of all accounts with balances below the average
at the bank.
delete from account where balance < (select avg (balance ) from
account )
Joins
• An SQL JOIN clause combines records from two or more tables in a
database. It creates a set that can be saved as a table or used as is.
A JOIN is a means for combining fields from two tables by using
values common to each.
RIGHT JOIN
Example: SELECT E.LNAME, E.DEPT,C.CONTACT FROM
CONCT_MASTER C RIGHT JOIN EMP_MASTER E ON
C.CODE_NO=E.EMP_NO;
or
SELECT E.LNAME, E.DEPT,C.CONTACT FROM
CONCT_MASTER C , EMP_MASTER E WHERE
C.CODE_NO(+)=E.EMP_NO;
Natural Join
• Example:
42
Id FirstName LastName UserName
IndividualId AccessLevel
1 Administrator Right Table
2 Contributor
3 Contributor
4 Contributor
Result Table
10 Administrator
IndividualId FirstName LastName UserName IndividualId AccessLevel
1 Fred Flinstone freddo 1 Administrator
2 Homer Simpson homey 2 Contributor
3 Homer Brown notsofamous 3 Contributor
4 Ozzy Osbourne sabbath 4 Contributor
5 Homer Gain noplacelike NULL NULL 43
Right Outer Join
Use this when you only want to return rows that have
matching data in the right table, even if there's no matching
rows in the left table.
SELECT * FROM Individual AS Ind
RIGHT JOIN Publisher AS Pb
ON Ind.IndividualId = Pb.IndividualId;
Or
SELECT Ind.FIRSTNAME, Ind.LASTNAME,Pb.Username,Pb.Accesslevel FROM
Individual Ind, Publisher Pb WHERE Ind.IndividualId (+)= Pb.IndividualId;
Result Table:
IndividualId FirstName LastName UserName IndividualId AccessLevel
1 Fred Flinstone freddo 1 Administrator
2 Homer Simpson homey 2 Contributor
3 Homer Brown notsofamous 3 Contributor
4 Ozzy Osbourne sabbath 4 Contributor
NULL NULL NULL NULL 10 Administrator
44
Cursors in SQL
• The Oracle Engine uses a work area for its internal processing in order to execute
an SQL statement . This work area is private to SQL’s operations and is called a
Cursor.
• The data that is stored in the cursor is called the Active Data Set.
• Conceptually the size of the cursor in memory is the size required to hold the
number of rows in the Active Data Set.
• For every SQL statement execution certain area in memory is allocated. This
private SQL area is called context area or cursor. A cursor acts as a handle or
pointer into the context area. A PL/SQL program controls the context area using
the cursor. Cursor represents a structure in memory and is different from cursor
variable.
• When we declare a cursor, we get a pointer variable, which does not point any
thing. When the cursor is opened, memory is allocated and the cursor structure is
created. The cursor variable now points the cursor. When the cursor is closed the
memory allocated for the cursor is released.
• Cursors allow the programmer to retrieve data from a table and perform actions
on that data one row at a time. There are two types of cursors:
• Implicit Cursors and
• Explicit cursors
Implicit Cursors
• For SQL queries returning single row PL/SQL declares implicit cursors. Implicit cursors are
simple SELECT statements and are written in the BEGIN block (executable section) of the
PL/SQL. Implicit cursors are easy to code, and they retrieve exactly one row. PL/SQL
implicitly declares cursors for all DML statements. The most commonly raised exceptions
here are NO_DATA_FOUND or TOO_MANY_ROWS.
• Implicit cursor attributes can be used to access information about the status of the
last insert, update, delete or single-row select statements.
Example :
BEGIN
UPDATE emp_master SET Branch_no=&branch_no where Emp_no=&emp_no;
If SQL%FOUND then
Dbms_output.put_line(‘Employee successfully transferred’);
ENDIF;
If SQL%NOTFOUND then
Dbms_output.put_line(‘employee no. does not exist’);
ENDIF
END;
Explicit Cursors
• Explicit cursors are used in queries that return multiple rows. The set of rows
fetched by a query is called active set. The size of the active set meets the search
criteria in the select statement. Explicit cursor is declared in the DECLARE section
of PL/SQL program.
Processing multiple rows is similar to file processing. For processing a file you need
to open it, process records and then close.
Similarly user-defined explicit cursor needs to be opened, before reading the
rows, after which it is closed. Like how file pointer marks current position in file
processing, cursor marks the current position in the active set.
Opening Cursor
Syntax: OPEN <cursor-name>;
Example : OPEN emp_cur;
• When a cursor is opened the active set is determined, the rows satisfying the
where clause in the select statement are added to the active set. A pointer is
established and points to the first row in the active set.
• Fetching from the cursor: To get the next row from the cursor we need to use fetch
statement.
Syntax: FETCH <cursor-name> INTO <variables>;
Example: FETCH emp_cur INTO ena;
FETCH statement retrieves one row at a time. Bulk collect clause need to be used to
fetch more than one row at a time.
Closing the cursor: After retrieving all the rows from active set the cursor should be
closed. Resources allocated for the cursor are now freed. Once the cursor is closed
the execution of fetch statement will lead to errors.
CLOSE <cursor-name>;
Explicit Cursor Attributes
• Every cursor defined by the user has 4 attributes. When appended
to the cursor name these attributes let the user access useful
information about the execution of a multi-row query.The
attributes are:
• The key strength of PL/SQL is its tight integration with the Oracle
database.
END;
Procedures
• Procedures are the same as Functions, in that they are
also used to perform some task with the difference being
that procedures cannot be used in a SQL statement and
although they can have multiple out parameters they do
not return a value. This is not always true for when an
NULL function is used.
Anonymous Blocks
Anonymous PL/SQL blocks can be embedded in an Oracle Pre-compiler or OCI
program. At run time, the program, lacking a local PL/SQL engine, sends these
blocks to the Oracle server, where they are compiled and executed. Likewise,
interactive tools such as SQL*Plus and Enterprise Manager, lacking a local PL/SQL
engine, must send anonymous blocks to Oracle.
Triggers
A trigger is a set of actions that run automatically when a
specified change operation is performed on a specified
table.
if deleting then
insert into audit_table values (‘Value1’,’DELETE’,sysdate);
Endif;
END; Audit_table
Name Type
TABLE_NAME VARCHAR2(10)
DML_OPERATION VARCHAR2(6)
DATE_OF_DML DATE 62
TYPES OF TRIGGRES
Row Trigger : A row trigger is fired each time in the table is affected
by triggering statement.
E.g. UPDATE statement updates multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE statement.
Statement Trigger:
It is fired once on behalf of the triggering statement , independent of
the number of rows the triggering statement affects.
Before Vs After Triggers
When defining a trigger it is necessary to specify the trigger timing,
i.e. specifying when the trigger action is to be executed in relation to
the triggering statement.
TYPES OF TRIGGRES
Before Trigger : it executes the trigger action before the triggering
statement.
After Trigger: it executes the trigger action after the triggering
statement is executed
Syntax : CREATE OR REPLACE TRIGGER <trigger name>
<BEFORE, AFTER>
{DELETE, INSERT, UPDATE [of Columnname]}
On <tablename>
Declare
:
Begin
<PL/SQL
End;
Creating Trigger
CREATE TRIGGER T1
AFTER UPDATE or DELETE on Cust_Master
FOR EACH ROW
DECLARE
BEGIN
PL/SQL statement
END;
Example:
• Loss of availability:
Some times called denial of service. When the database is not available
it incurs a loss .So any threat that gives rise to time offline, even to
check whether something has occurred, is to be avoided.
Categories of specific regulatory threats to
database systems
• Commercial sensitivity:
Most financial losses through fraud arise from employees. Access
controls provide both protection against criminal acts and evidence of
attempts (successful or otherwise) to carry out acts detrimental to the
organisation, whether fraud, extraction of sensitive data or loss of
availability.
• Personal privacy and data protection: Internationally, personal data is
normally subject to legislative controls. Personal data is data about an
identifiable individual. Often the individual has to be alive but the
method of identification is not prescribed. So a postal code for a home
may in some cases identify an individual, if only one person is living at
an address with the postal code. Such data needs careful handling and
control.
Categories of specific regulatory threats to database
systems
• Computer misuse:
There is also generally legislation on the misuse of computers. Misuse
includes the violation of access controls and attempts to cause damage
by changing the database state or introducing worms and viruses to
interfere with proper operation. These offences are often extraditable.
So an unauthorised access in India using computers in France to access
databases in Germany which refer to databases in America could lead
to extradition to France or Germany or the USA.
•Audit requirements:
These are operational constraints built around the need to know who
did what, who tried to do what, and where and when everything
happened. They involve the detection of events (including CONNECT
and GRANT transactions), providing evidence for detection, assurance as
well as either defence or prosecution. There are issues related to
computer-generated evidence.
Authentication and Authorization
Access to IT resources generally requires a log-in process that is trusted
to be secure. Most of what follows is directly about Relational client-
server systems. Other system models differ to a greater or lesser extent,
though the underlying principles remain true.
Authentication
✓ The client has to establish the identity of the server and the server
has to establish the identity of the client. This is done often by means
of shared secrets (either a password/user-id combination, or shared
biographic and/or biometric data).
✓ It can also be achieved by a system of higher authority which has
previously established authentication.
✓ In client-server systems where data (not necessarily the database) is
distributed, the authentication may be acceptable from a peer
system. Note that authentication may be transmissible from system
to system. The result, as far as the DBMS is concerned, is an
authorization-identifier.
Authentication does not give any privileges for particular tasks. It only
establishes that the DBMS trusts that the user is who he claimed to be
and that the user trusts that the DBMS is also the intended system.
Authentication is a prerequisite for authorization.
Authorization
Authorization relates to the permissions granted to an authorized user to
carry out particular transactions, and hence to change the state of the
database(write item transactions) and/or receive data from the database
(read-item transactions). The result of authorization, which needs to be
on a transactional basis, is a vector: Authorization.
Authorization
Forms of authorization on (parts of) the database:
• Read authorization - allows reading, but not
modification of data.
• Insert authorization - allows insertion of new data, but
not modification of existing data.
• Update authorization - allows modification, but not
deletion of data.
• Delete authorization - allows deletion of data
Security Specification in SQL
• The grant statement is used to confer authorization
grant <privilege list>
on <relation name or view name> to <user list>
• <user list> is:
• a user-id
• public, which allows all valid users the privilege granted
• Granting a privilege on a view does not imply granting
any privileges on the underlying relations.
• The grantor of the privilege must already hold the
privilege on the specified item (or be the database
administrator).
Privileges in SQL
• select: allows read access to relation,or the ability to
query using the view
• Example: grant users U1, U2, and U3 select authorization on the
branch relation:
grant select on branch to U1, U2, U3
• insert: the ability to insert tuples
• update: the ability to update using the SQL update
statement
• delete: the ability to delete tuples.
• references: ability to declare foreign keys when creating
relations.
• all privileges: used as a short form for all the allowable
privileges
Privilege To Grant Privileges
AP**
A owns the
object on
which P is
a privilege
Example: Grant Diagram
AP** BP*
A owns the A:
object on GRANT P
which P is
TO B WITH
a privilege
GRANT OPTION
Example: Grant Diagram
B:
GRANT P
TO C WITH
AP** BP* CP* GRANT OPTION
A owns the A:
object on GRANT P
which P is
TO B WITH
a privilege
GRANT OPTION
Example: Grant Diagram
B:
GRANT P
TO C WITH
AP** BP* CP* GRANT OPTION
A owns the A:
object on GRANT P CP
which P is
TO B WITH
a privilege
GRANT OPTION A:
GRANT P
TO C
Example: Grant Diagram
A executes
REVOKE P FROM B CASCADE;
Clusters can be used to store data form different tables in the same
physical data blocks, they are appropriate to use if the records from
those tables are frequently queried together. By storing them in the
same data blocks, the number of database block reads needed to
fullfill such queries decreases, there by improving performance.
Packages
• Packages are groups of conceptually linked Functions,
Procedures,Variable,Constants & Cursors etc.