0% found this document useful (0 votes)
16 views108 pages

SQL & PL/SQL: Commands and Concepts

Uploaded by

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

SQL & PL/SQL: Commands and Concepts

Uploaded by

ns4826
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 108

18CSC303J – Database Management

Systems

Unit III – SQL & PL/SQL


Course Learning Outcome (CLO)

• Apply the knowledge to create, store and


retrieve data using Structure Query Language
(SQL) and PL/SQL
Topics Covered
• Basics of SQL- DDL,DML,TCL
• Structure Creation
• Constraints
• Functions-Built-in , Aggregate
• Subqueries
• Set operations
• Triggers
• Query processing
• Transaction control commands
• Views
• PL/SQL
Basics of SQL-
DDL,DML,DCL,TCL
SQL
• Structured Query Language(SQL) as we all know is the database
language by the use of which we can perform certain operations
on the existing database and also we can use this language to
create a database. SQL uses certain commands like Create,
Drop, Insert etc. to carry out the required tasks.
• These SQL commands are mainly categorized into four
categories as:
 DDL – Data Definition Language
 DML – Data Manipulation Language
 DCL – Data Control Language
 TCL – Transaction Control Language
DDL
Introduction
DDL is short name of Data Definition Language, which
deals with database schemas and descriptions, of how the data
should reside in the database.
• CREATE - to create a database and its objects like (table,
index, views, store procedure, function, and triggers)
• ALTER - alters the structure of the existing database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including
all spaces allocated for the records are removed
• COMMENT - add comments to the data dictionary
• RENAME - rename an object
DML
Introduction
DML is short name of Data Manipulation
Language which deals with data manipulation and
includes most common SQL statements such SELECT,
INSERT, UPDATE, DELETE, etc., and it is used to
store, modify, retrieve, delete and update data in a
database.
• SELECT - retrieve data from a database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - Delete all records from a database table
DCL
Introduction
• DCL is short name of Data Control Language which
includes commands such as GRANT and mostly
concerned with rights, permissions and other controls of
the database system.
• GRANT - allow users access privileges to the database
• REVOKE - withdraw users access privileges given by
using the GRANT command
TCL
Introduction
• TCL is short name of Transaction Control Language
which deals with a transaction within a database.
• COMMIT - commits a Transaction
• ROLLBACK - rollback a transaction in case of any error
occurs
• SAVEPOINT - to rollback the transaction making points
within groups
• SET TRANSACTION - specify characteristics of the
transaction
DDL-Structure creation
Creating a Table
• Syntax
CREATE TABLE table_name
(Column_name datatype[(size)],
Column_name datatype[(size)],
);
• Example
CREATE TABLE stud
(Regno varchar2(10),
Name char(50),
DOB date,
Address varchar2(50));
Creates a table with four columns
Data Types
• Following broad categories of data types exist in most
databases:
– String Data
– Numeric Data
– Temporal Data
– Large Objects
String Data
• Fixed Length:
Occupies the same length of space in memory no matter
how much data is stored in them.
• Syntax:
char(n) where n is the length of the String
e.g. name char(50)

If the variable stored for name is ‘Sanjay’ the extra 43 fields are
padded with blanks
String Data
• Variable Length string is specified with maximum length of
characters possible in the string, however, the allocation is sized
to the size of the data stored in memory.
• Syntax:
Varchar(n) – n is the maximum length of data possible for the type

There may be a restriction in the maximum length of the data that you
can specify in the declaration which will vary according to the
database.
All character data has to be enclosed in single quotes during
specification.
Numeric Data Types
• Store all the data related to purely numeric data.
• Some numeric data may also be stored as a character field e.g. zip
codes
• Common Numeric Types:
– Decimal Floating point number
– Float Floating point number
– Integer(size) Integer of specified length
– Money A number which contains exactly two
digits after the decimal point
– Number A standard number field that can hold
a floating point data

Note: Different databases name their numeric fields differently and may
not support all numeric types. They may also support additional
numeric types.
Temporal Data Types
• These represent the dates and time:
• Three basic types are supported:
– Dates
– Times
– Date-Time Combinations
Large Data Objects
• These are used for storing data objects like files and images:
• There are two types:
– Character Large Objects (clobs)
– Binary Large Objects (blobs)
Alter Statement
• Alter Statement:
– used to make changes to the schema of the table. Columns can be
added and the data type of the columns changed as long as the
data in those columns conforms to the data type specified.

1. ALTER TABLE - ADD Column

• Syntax:
ALTER TABLE table_name
ADD column_name datatype;
• Example:
ALTER TABLE stud
ADD (Age number(2),
ADD Mark1 number(3),
ADD Mark2 number(3));

The stud table is already exist and then we added three more
columns Age ,Mark1 and Mark2 respectively, by the use of above
command.
Alter Statement(contd..)
2. ALTER TABLE - DROP COLUMN

• Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
• Example:
ALTER TABLE stud
DROP COLUMN Mark2;
This command will drop particular column mark2.

3. ALTER TABLE - ALTER/MODIFY COLUMN


• Syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
• Example:
ALTER TABLE stud
MODIFY (Name varchar2(60));
The Name column already exist in stud table, it was char and size 50, now it
is modified by varchar2 and size 60.
Drop Table Statement
DROP TABLE
-Drop an existing table in a database.

• Syntax:
DROP TABLE table_name;

• Example:
DROP TABLE stud;

This will destroy the table and all data which will be recorded in
it.
Truncate Table Statement
TRUNCATE TABLE
-Truncates the contents in an existing table in a database.

• Syntax:
TRUNCATE TABLE table_name;

• Example:
TRUNCATE TABLE stud;

This will delete the contents in the table. But structure remains
the same
Rename Table Statement
RENAME TABLE
-Truncates the contents in an existing table in a database.

• Syntax:
RENAME OldTableName
TO NewTableName;

• Example:
RENAME stud
TO student;

The old name table was stud now new name is the student.
DML-Data Manipulation
Language
Select Statement
• To display only selected fields
Syntax:
SELECT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the field names of the table you want
to select data from
Example
SELECT name, age FROM stud;

• To display all the fields available in the table


Syntax:
SELECT * FROM table_name;
Example
SELECT * FROM stud;
Insert Statement
• The INSERT INTO statement is used to insert new records in a
table.
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example
INSERT INTO stud VALUES (100, ‘Asha’, ‘27-Jan-2021’, ‘First Street’, 15,
89, 90);
1 row will be created
• Insert NULL Value to a column
INSERT INTO stud VALUES (101, ‘Alex’, ‘27-feb-2021’, ‘Second Street’,
null, 98, 79);
The above command will insert null to age column.
• Insert Default value to a column
INSERT into Student values(103,'Chris')
Suppose the age column of student table has default value of 14.
Also, if you run the below query, it will insert default value into the age column, whatever the
default value may be.
Where Clause
• Where clause is used to specify condition while retrieving data
from table. Where clause is used mostly with
Select, Update and Delete query. If condition specified
by where clause is true then only the result from table is returned.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
SELECT regno, name
FROM stud WHERE regno=101;
This displays only the regno and name of the stud with regno 101.

SELECT *FROM stud WHERE regno=101;


This displays the all the details of the stud with regno 101.
Update Statement
• The UPDATE statement is used to modify the existing records in a
table..
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;;
Example
UPDATE stud
SET name = 'Alfred ', age= 15
WHERE regno = 103;

The above command will update two columns of a record.


Delete Statement
• The DELETE statement is used to delete all records in a table.
Syntax:
DELETE FROM table_name;
Example
DELETE FROM stud;

• Delete command can also be used with condition to delete a


particular row
Syntax:
DELETE FROM table_name
WHERE condition;
Example
DELETE FROM stud
WHERE regno=105;
Constraints

• Defining Constraints-Primary Key, Foreign Key,


Unique, not null, check, IN operator
Constraints
• Integrity constraints ensure that changes made to the
database do not result in a loss of data consistency.
• Examples:
• An instructor name cannot be null.
• No two instructors can have the same instructor ID.
• Every department name in the course relation must
have a matching department name in the department
relation.
• The budget of a department must be greater than
$0.00.
• integrity constraints that can be tested with minimal
overhead (cost).
Constraints
• (1) Integrity constraints are declared as part of the
create table command
• (2) Integrity constraints can also be added to an
existing relation by using
alter table table-name add constraint

Constraints on a Single Relation


• primary key
• not null
• unique
• check(<predicate>)
Constraints
The general form of the create table command is:
create table r
(A1 D1,
A2 D2,
...,
An Dn,
integrity-constraint1,
...,
integrity-constraintk);
• where r is the name of the relation, each Ai is the name of an attribute in the schema of
relation r, and Di is the domain of attribute Ai; that is, Di specifies the type of attribute
Ai along with optional constraints that restrict the set of allowed values for Ai .
Constraints
Primary key
• primary key (Aj1 , Aj2, . . . , Ajm ): The attributes Aj1 , Aj2, . . . , Ajm form the
primary key for the relation. The primary key attributes are required to be not
null and unique;

• foreign key (Ak1 , Ak2, . . . , Akn ) references s: The values of attributes (Ak1 ,
Ak2, . . . , Akn ) for any tuple in the relation must correspond to values of the
primary key attributes of some tuple in relation s.
Constraints
Example:
create table department
(dept name varchar (20),
building varchar (15),
budget numeric (12,2),
primary key (dept name));

create table course


(course id varchar (7),
title varchar (50),
dept name varchar (20),
credits numeric (2,0),
primary key (course id),
foreign key (dept name) references department);
Constraints
Not Null Constraint
• For certain attributes, null values may be inappropriate.
• prohibits the insertion of a null value for the attribute. That is the null
value is not allowed for that attribute.

Example:
create table instructor
(ID varchar (5),
name varchar (20) not null,
dept name varchar (20),
salary numeric (8,2),
primary key (ID),
foreign key (dept name) references department);
Constraints
Unique Constraint
• unique (Aj1 , Aj2, . . . , Ajm )
• attributes Aj1 , Aj2, . . . , Ajm form a candidate
key; that is, no two tuples in the relation can be
equal on all the listed attributes.
Constraints
The check Clause
• The clause check(P) specifies a predicate P that must be satisfied by every
tuple in a relation.
• ensure that attribute values satisfy specified conditions
• Example:
create table section
(course id varchar (8),
sec id varchar (8),
semester varchar (6),
year numeric (4,0),
building varchar (15),
room number varchar (7),
time slot id varchar (4),
primary key (course id, sec id, semester, year),
check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)));
Constraints
Referential Integrity
• ensure that a value in one relation for a given set of attributes also appears for
a certain set of attributes in another relation.
• Foreign keys can be specified as part of the SQL create table statement by
using the foreign key clause
• Example: “foreign key (dept name) references department”
• Let r1 and r2 be relations whose set of attributes are R1 and R2, respectively,
with primary keys K1 and K2. The subset of R2 is a foreign key referencing K1
in relation r1 if it is required that, for every tuple t2 in r2, there must be a
tuple t1 in r1 such that t1.K1 = t2..
Constraints
Referential Integrity
create table department
(dept name varchar (20),
building varchar (15),
budget numeric (12,2) check (budget > 0),
primary key (dept name))

create table course


(course id varchar (8),
title varchar (50),
dept name varchar (20),
credits numeric (2,0) check (credits > 0),
primary key (course id),
foreign key (dept name) references department)
Constraints
SQL
Built-in Functions
What are Built-In Functions?
 In SQL a built-in function is a piece for programming that takes zero or
more inputs and returns a value.
 An example of a built-in function is ABS(), which when given a value
calculates the absolute (non-negative) value of the number.
 ABS () are used to perform calculations.
 GETDATE () are used to obtain a system value, such as the current data.
 LEFT (), are used to manipulate textual data.

SELECT Name,
ABS(500 - ReorderPoint)
ReorderPointDeviation
FROM
production.Product
WHERE ABS(500 -
ReorderPoint) > 200
Function Categories
 Numeric Functions – perform advanced calculations and round numbers.
 String Functions – change text values to all upper case, or remove the
trailing spaces from values.
 Conversion Functions – Convert data with CAST and CONVERT
 Group Functions- functions that operate on groups of rows and return one
value for the entire group
 Date Functions – add days or months to a date. Calculate the day of the
week from the date.
Numeric Functions
Function Input Argument Value Returned
ABS ( m ) m = value Absolute value of m
MOD ( m, n ) m = value, n = divisor Remainder of m divided by n
POWER ( m, n ) m = value, n = exponent m raised to the nth power
ROUND ( m [, n ] ) m = value, n = number of decimal places, default 0 m rounded to the nth decimal place
TRUNC ( m [, n ] ) m = value, n = number of decimal places, default 0 m truncated to the nth decimal place
SIN ( n ) n = angle expressed in radians sine (n)
COS ( n ) n = angle expressed in radians cosine (n)
TAN ( n ) n = angle expressed in radians tan (n)
ASIN ( n ) n is in the range -1 to +1 arc sine of n in the range -π/2 to +π/2
ACOS ( n ) n is in the range -1 to +1 arc cosine of n in the range 0 to π
ATAN ( n ) n is unbounded arc tangent of n in the range -π/2 to + π/2
SINH ( n ) n = value hyperbolic sine of n
COSH ( n ) n = value hyperbolic cosine of n
TANH ( n ) n = value hyperbolic tangent of n
SQRT ( n ) n = value positive square root of n
EXP ( n ) n = value e raised to the power n
LN ( n ) n>0 natural logarithm of n
LOG ( n2, n1 ) base n2 any positive value other than 0 or 1, n1 any positive value logarithm of n1, base n2
CEIL ( n ) n = value smallest integer greater than or equal to n
FLOOR ( n ) n = value greatest integer smaller than or equal to n
SIGN ( n ) n = value -1 if n < 0, 0 if n = 0, and 1 if n > 0
Here are some examples of the use of some of these numeric functions:

select round (83.28749, 2) from dual;

select sqrt (3.67) from dual;

power (2.512, 5) from dual;

select

• String Functions
Function Input Argument Value Returned

INITCAP ( s ) s = character string First letter of each word is changed to uppercase


and all other letters are in lower case.
LOWER ( s ) s = character string All letters are changed to lowercase.
UPPER ( s ) s = character string All letters are changed to uppercase.
CONCAT ( s1, s2 ) s1 and s2 are character strings Concatenation of s1 and s2. Equivalent to s1 || s2

LPAD ( s1, n [, s2] ) s1 and s2 are character strings and n is an integer value Returns s1 right justified and padded left with n
characters from s2; s2 defaults to space.
RPAD ( s1, n [, s2] ) s1 and s2 are character strings and n is an integer value Returns s1 left justified and padded right with n
characters from s2; s2 defaults to space.
LTRIM ( s [, set ] ) s is a character string and set is a set of characters Returns s with characters removed up to the first
character not in set; defaults to space
RTRIM ( s [, set ] ) s is a character string and set is a set of characters Returns s with final characters removed after the
last character not in set; defaults to space
String Functions
Returns s with every occurrence of search_s
REPLACE ( s, search_s [, s = character string, search_s = target string,
in s replaced by replace_s; default removes
replace_s ] ) replace_s = replacement string
search_s
Returns a substring from s, beginning in
SUBSTR ( s, m [, n ] ) s = character string, m = beginning position, n = position m and n characters long; default
number of characters returns to end of s.
LENGTH ( s ) s = character string Returns the number of characters in s.
Returns the position of the nth occurrence of
INSTR ( s1, s2 [, m [, n ] ] ) s1 and s2 are character strings, m = beginning
s2 in s1, beginning at position m, both m and
position, n = occurrence of s2 in s1
n default to 1.

Here are some examples of the use of String functions:

select concat ('Alan', 'Turing') as "NAME" from dual;

select 'Alan' || 'Turing' as "NAME" from dual;

select initcap ("now is the time for all good men to come to the aid
of the party") as "SLOGAN" from dual;

select substr ('Alan Turing', 1, 4) as "FIRST" from dual;


String / Number Conversion
Functions
Function Input Argument Value Returned
NANVL ( n2, n1 ) n1, n2 = value if (n2 = NaN) returns n1 else returns n2

TO_CHAR ( m [, fmt ] ) m = numeric value, fmt = format Number m converted to character string as specified by
the format
TO_NUMBER ( s [, fmt ] ) s = character string, fmt = format Character string s converted to a number as specified by
the format

Formats for TO_CHAR Function


Symbol Explanation
9 Each 9 represents one digit in the result
0 Represents a leading zero to be displayed
$ Floating dollar sign printed to the left of number
L Any local floating currency symbol
. Prints the decimal point
, Prints the comma to represent thousands
Group Functions
Function Input Argument Value Returned
AVG ( [ DISTINCT | ALL ] col ) col = column name The average value of that column

COUNT ( * ) none Number of rows returned including


duplicates and NULLs
COUNT ( [ DISTINCT | ALL ] col ) col = column name Number of rows where the value of the
column is not NULL
MAX ( [ DISTINCT | ALL ] col ) col = column name Maximum value in the column
MIN ( [ DISTINCT | ALL ] col ) col = column name Minimum value in the column
SUM ( [ DISTINCT | ALL ] col ) col = column name Sum of the values in the column

CORR ( e1, e2 ) e1 and e2 are column names Correlation coefficient between the two
columns after eliminating nulls
MEDIAN ( col ) col = column name Middle value in the sorted column,
interpolating if necessary
STDDEV ( [ DISTINCT | ALL ] col ) col = column name Standard deviation of the column ignoring
NULL values
VARIANCE ( [ DISTINCT | ALL ] col ) col = column name Variance of the column ignoring NULL
values
 SQL AVG():
 This function is used to get the average value of a numeric column.
 To get the average salary, the query would be
 SELECT AVG (salary) FROM employee;

 SQL COUNT ():


 This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not
specified, then the query returns the total number of rows in the table.
 For Example: If you want the number of employees in a particular
department, the query would be:
 SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
 The output would be '2' rows.
 If you want the total number of employees in all the department, the
query would take the form:
 SELECT COUNT (*) FROM employee;
 The output would be '5' rows

 SQL DISTINCT ():


 This function is used to select the distinct rows.
For Example:

 If you want to select all distinct department names from employee


table, the query would be:
 SELECT DISTINCT dept FROM employee;
 To get the count of employees with unique name, the query would be:
 SELECT COUNT (DISTINCT name) FROM employee;

 SQL MAX ():


 This function is used to get the maximum value from a column.
 To get the maximum salary drawn by an employee, the query
would be:
 SELECT MAX (salary) FROM employee;
 SQL MIN ():
 This function is used to get the minimum value from a column.
 To get the minimum salary drawn by an employee, he query
would be:
 SELECT MIN (salary) FROM employee;

 SQL SUM ():


 This function is used to get the sum of a numeric column
 To get the total salary given out to the employees,
 SELECT SUM (salary) FROM employee;
Date and Time Functions
Function Input Argument Value Returned
ADD_MONTHS ( d, n ) d = date, n = number of months Date d plus n months
LAST_DAY ( d ) d = date Date of the last day of the month containing d
MONTHS_BETWEEN ( d, e ) d and e are dates Number of months by which e precedes d

NEW_TIME ( d, a, b ) d = date, a = time zone (char), b = time The date and time in time zone b when date d
zone (char) is for time zone a
NEXT_DAY ( d, day ) d = date, day = day of the week Date of the first day of the week after d
SYSDATE none Current date and time
GREATEST ( d1, d2, ..., dn ) d1 ... dn = list of dates Latest of the given dates
LEAST ( d1, d2, ..., dn ) d1 ... dn = list of dates Earliest of the given dates

Date Conversion Functions


Function Input Argument Value Returned

TO_CHAR ( d [, fmt ] ) d = date value, fmt = format for string The date d converted to a string in the
given format
TO_DATE ( s [, fmt ] ) s = character string, fmt = format for date String s converted to a date value

ROUND ( d [, fmt ] ) d = date value, fmt = format for string Date d rounded as specified by the
format
TRUNC ( d [, fmt ] ) d = date value, fmt = format for string Date d truncated as specified by the
format
Date Formats
Format Code Description Range of Values
DD Day of the month 1 - 31
DY Name of the day in 3 uppercase letters SUN, ..., SAT
DAY Complete name of the day in uppercase, padded to 9 characters SUNDAY, ..., SATURDAY
MM Number of the month 1 - 12
MON Name of the month in 3 uppercase letters JAN, ..., DEC
MONTH Name of the month in uppercase padded to a length of 9 characters JANUARY, ..., DECEMBER
RM Roman numeral for the month I, ..., XII
YY or YYYY Two or four digit year 71 or 1971
HH:MI:SS Hours : Minutes : Seconds 10:28:53
HH 12 or HH 24 Hour displayed in 12 or 24 hour format 1 - 12 or 1 - 24
MI Minutes of the hour 0 - 59
SS Seconds of the minute 0 - 59
AM or PM Meridian indicator AM or PM
SP A suffix that forces the number to be spelled out. e.g. TWO THOUSAND NINE
TH A suffix meaning that the ordinal number is to be added e.g. 1st, 2nd, 3rd, ...
FM Prefix to DAY or MONTH or YEAR to suppress padding e.g. MONDAY with no extra spaces at the end
Here are some examples of the use of the Date functions:

select to_char ( sysdate, 'MON DD, YYYY' ) from dual;

select to_char ( sysdate, 'HH12:MI:SS AM' ) from dual;

select to_char( new_time(sysdate,'CDT','GMT'),'HH24:MI')from dual;

select greatest (to_date ( 'JAN 19, 2000', 'MON DD, YYYY' ),


to_date ( 'SEP 27, 1999', 'MON DD, YYYY' ),
to_date ( '13-Mar-2009', 'DD-Mon-YYYY' ) )
from dual;

select next_day ( sysdate, 'FRIDAY' ) from dual;


Subqueries

Unit 3 DBMS
Subqueries
• A query can be processed inside another
query.
• A subquery is select statement that is
embedded in the clause of another select
statement
• Inner query and outer query : inner query
returns a value that is used by outer query.

Unit 3 DBMS
Syntax for subquery

Unit 3 DBMS
Ex..
• Who is earning more salary than Mr.John?
• Need to find the John salary first (inner query)
then compare the value with others salary
(outer query)

select salary from emp where salary >


(select salary from emp
where ename=“Mr.John”);
Unit 3 DBMS
SUB-QUERIES OR NESTED QUERIES
Display the employee name who is getting the minimum salary.

SQL> select empname from employees where salary =(select min(salary) from
employees);
EMPNAME
--------------------
Mark
Nadia
Nadal
Diwaagar
Charles

Unit 3 DBMS
SUB-QUERIES OR NESTED QUERIES

Who is the youngest male employee


SQL> select empname,dob from employees where dob=(select max(dob)
from employees where sex='Male');

EMPNAME DOB
-------------------- ---------
charles 29-DEC-98

Unit 3 DBMS
Using Having clause..
Select departmentid,min(salary) from emp
group by departmentid
Having min(salary) >
(select min(salary) from emp where
departmentid=50);

This query returns all departments minimum salary


that has greater than the minimum salary of
department id is 50
Unit 3 DBMS
Set Operations
• The set operations union, intersect, and except operate on relations and
correspond to the relational algebra operations 
• Each of the above operations automatically eliminates duplicates; to retain all
duplicates use the corresponding multiset versions union all, intersect all and
except all.

Unit 3 DBMS
Set Operations
• Find all customers who have a loan, an account, or both:
(select customer-name from depositor)
union
(select customer-name from borrower)
 Find all customers who have both a loan and an account.
(select customer-name from depositor)
intersect
(select customer-name from borrower)
 Find all customers who have an account but no loan.

(select customer-name from depositor)


except
(select customer-name from borrower)

Unit 3 DBMS
Views
• It is not necessary for all users to see the entire logical model (that is, all
the actual relations stored in the database.)
• Consider a person who needs to know an instructors name and
department, but not the salary. This person should see a relation
described, in SQL, by

select ID, name, dept_name


from instructor

• A view provides a mechanism to hide certain data from the view of certain
users.
• Any relation that is not of the conceptual model but is made visible to a
user as a “virtual relation” is called a view.

Unit 3 DBMS
View Creation
• A view is defined using the create view statement which has the form
create view v as < query expression >
where <query expression> is any legal SQL expression. The view name is
represented by v.
• Once a view is defined, the view name can be used to refer to the virtual
relation that the view generates.
• View definition is not the same as creating a new relation by evaluating
the query expression
– Rather, a view definition causes the saving of an expression; the
expression is substituted into queries using the view.

Unit 3 DBMS
Display view details
• A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
• Find all instructors in the Biology department
select name
from faculty
where dept_name = 'Biology'
• Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;

Unit 3 DBMS
• One view may be used in the expression defining another view

• A view relation v1 is said to depend directly on a view relation v2 if v2 is

used in the expression defining v1

• A view relation v1 is said to depend on view relation v2 if either v1 depends

directly to v2 or there is a path of dependencies from v1 to v2

• A view relation v is said to be recursive if it depends on itself.

Unit 3 DBMS
Materialized Views
• Certain database systems allow view relations to be physically stored.

– Physical copy created when the view is defined.

– Such views are called Materialized view:

• If relations used in the query are updated, the materialized view result becomes out of

date

– Need to maintain the view, by updating the view whenever the underlying

relations are updated.

Unit 3 DBMS
View Update
• Add a new tuple to faculty view which we defined earlier
insert into faculty

values ('30765', 'Green', 'Music');


• This insertion must be represented by the insertion into the instructor relation
– Must have a value for salary.
• Two approaches
– Reject the insert
– Inset the tuple

('30765', 'Green', 'Music', null)


into the instructor relation

Unit 3 DBMS
Update Views Rules

• Most SQL implementations allow updates only on simple views

– The from clause has only one database relation.

– The select clause contains only attribute names of the relation, and

does not have any expressions, aggregates, or distinct specification.

– Any attribute not listed in the select clause can be set to null

– The query does not have a group by or having clause.

Unit 3 DBMS
Transaction
• A transaction consists of a sequence of query and/or update statements
and is a “unit” of work
• The SQL standard specifies that a transaction begins implicitly when an
SQL statement is executed.
• The transaction must end with one of the following statements:
– Commit work. The updates performed by the transaction become
permanent in the database.
– Rollback work. All the updates performed by the SQL statements in
the transaction are undone.
• Atomic transaction
– either fully executed or rolled back as if it never occurred
• Isolation from concurrent transactions

Unit 3 DBMS
Triggers
• A trigger is a stored procedure in database which automatically invokes
whenever a special event in the database occurs. For example, a trigger
can be invoked when a row is inserted into a specified table or when
certain table columns are being updated.
• Triggers are composed to be executed in light of any of the
accompanying occasions.
 A database control (DML) statement (DELETE, INSERT, or UPDATE).

 A database definition (DDL) statement (CREATE, ALTER, or DROP).

 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or


SHUTDOWN).
The syntax of Triggers in SQL–
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Create [OR REPLACE] TRIGGER trigger_name: It makes or replaces a
current trigger with the trigger_name.
EXAMPLE
CREATE OR REPLACE TRIGGER display_salary_changes
AFTER 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;
After creating a Trigger, use it in the PL/SQL code for putting it in to action.

DECLARE

total_rows number(2);

BEGIN

UPDATE customers

SET salary = salary + 5000;

IF sql%notfound THEN

dbms_output.put_line('no customers updated');

ELSIF sql%found THEN

total_rows := sql%rowcount;

dbms_output.put_line( total_rows || ' customers updated ');

END IF;

END;
Advantages of Triggers

•Triggers can be written for the following purposes −

•Generating some derived column values automatically

•Enforcing referential integrity

•Event logging and storing information on table access

•Auditing

•Synchronous replication of tables

•Imposing security authorizations

•Preventing invalid transactions


Basic Steps in Query Processing
Query Processing is the activity performed in extracting data from the database. In query processing, it
takes various steps for fetching the data from the database.

1. Parsing and translation


2. Optimization
3. Evaluation
Basic Steps in Query Processing (Cont.)

• Parsing and translation

– translate the query into its internal form. This is then

translated into relational algebra.

– Parser checks syntax, verifies relations

• Evaluation

– The query-execution engine takes a query-evaluation

plan, executes that plan, and returns the answers to the

query.
Basic Steps in Query Processing : Optimization

• A relational algebra expression may have many equivalent expressions


– E.g., salary75000(salary(instructor)) is equivalent to

salary(salary75000(instructor))
• Each relational algebra operation can be evaluated using one of
several different algorithms
– Correspondingly, a relational-algebra expression can be evaluated
in many ways.
• Annotated expression specifying detailed evaluation strategy is called
an evaluation-plan.
– E.g., can use an index on salary to find instructors with salary <
75000,
– or can perform complete relation scan and discard instructors
with salary  75000
Basic Steps: Optimization (Cont.)

• Query Optimization: Amongst all equivalent evaluation plans choose the

one with lowest cost.

– Cost is estimated using statistical information from the

database catalog

• e.g. number of tuples in each relation, size of tuples, etc.


Introduction to PL/SQL
• Procedural Language extension for SQL
• Oracle Proprietary
• 3GL Capabilities
• Integration of SQL
• Portable within Oracle data bases
• Callable from any client
Structure of PL/SQL
• PL/SQL is Block Structured

A block is the basic unit from which all PL/SQL programs are built. A block
can be named (functions and procedures) or anonymous
• Sections of block

1- Header Section

2- Declaration Section

3- Executable Section

4- Exception Section
Structure of PL/SQL
HEADER

Type and Name of block

DECLARE

Variables; Constants; Cursors;

BEGIN

PL/SQL and SQL Statements

EXCEPTION

Exception handlers

END;
Structure of PL/SQL
DECLARE
a number;
text1 varchar2(20);
text2 varchar2(20) := “HI”;
BEGIN
---------- ---------- ----------
END;

Important Data Types in PL/SQL include NUMBER, INTEGER,


CHAR, VARCHAR2, DATE etc
to_date(‘02-05-2007','dd-mm-yyyy') { Converts String to Date}
Structure of PL/SQL

• Data Types for specific columns

Variable_name Table_name.Column_name%type;

This syntax defines a variable of the type of the referenced


column on the referenced table
PL/SQL Control Structure
• PL/SQL has a number of control structures which includes:

• Conditional controls
• Iterative or loop controls.
• Exception or error controls

• It is these controls, used singly or together, that allow the PL/SQL


developer to direct the flow of execution through the program.
PL/SQL Control Structure

• Conditional Controls

IF....THEN....END IF;

IF....THEN...ELSE....END IF;

IF....THEN...ELSIF....THEN....ELSE....END IF;
PL/SQL Control Structure
• LOOP
...SQL Statements...
EXIT;
END LOOP;

• WHILE loops
• WHILE condition LOOP
...SQL Statements...
END LOOP;

• FOR loops
• FOR <variable(numeric)> IN [REVERSE] <lowerbound>..<upperbound>
LOOP .... ..... END LOOP;
Cont..
• PL/SQL is a completely portable, high-
performance transaction-processing
language.
• PL/SQL provides a built-in, interpreted and
OS independent programming
environment.
• PL/SQL can also directly be called from
the command-line SQL*Plus interface.
DECLARE message varchar2(20):= 'Hello, World!'; BEGIN dbms_output.put_line(message); END; /
Cont..
• DECLARE ;
• BEGIN IF(CONDITION)
• THEN ;
• END;
Cont..
• Coding for If Statement:
• DECLARE
• b number;
• c number;
• BEGIN
• B:=10;
• C:=20;
• if(C>B) THEN
• dbms_output.put_line('C is maximum');
• end if;
• end;
• /
PL/SQL Control Structure
• Cursor
DECLARE
name varchar2(20);
Cursor c1 is
select t.name
from table t
where date is not null;
BEGIN
OPEN c1;
LOOP
FETCH c1 into name;
exit when c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;
Debuging

• show error

• DBMS_OUTPUT.PUT_LINE(‘ .. ‘);
Execution
• How to execute a function in PL/SQL?
Var issue_flag number;
exec :issue_flag:=fun_name(arg1,arg2,. . . .);
PRINT :issue_flag;
• How to execute a procedure in PL/SQL?
Exec procedure_name(arg1,arg2,. . . .);
PL_SQL CURSOR
• 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.
• There are two types of cursors :
1. Implicit cursors
2. Explicit cursors
Cont..
Explicit cursor

CURSOR cursor_name IS
select_statement;

CURSOR c_customers IS SELECT id, name,


address FROM customers;

OPEN c_customers;
FETCH c_customers INTO c_id, c_name, c_addr;

CLOSE c_customers;
Cursor program
DECLARE c_id emp.eid%type;
c_name emp.ename%type;
c_sal emp.salary%type;
CURSOR c_customers is SELECT eid, ename, salary FROM emp;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_sal;
EXIT
WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' ||
c_sal);
END LOOP;
CLOSE c_customers;
END;
/
References
1. http://www.csee.umbc.edu/help/oracle8/server.815/a67842/01_oview.htm#740
2. http://en.wikipedia.org/wiki/PL/SQL
3. http://www.skillbuilders.com/Tutorials-V2/ora9i_Intro_to_PLSQL/ora9i_Intro_to_PLSQL.cfm
4. http://www.databasejournal.com/features/mysql/article.php/ 3569846/MySQL-Stored-Functions.htm

5. http://www.mysqltutorial.org/mysql-stored-function/

6. https://dev.mysql.com/doc/refman/5.7/en/create- procedure.html
THANK YOU

You might also like