0% found this document useful (0 votes)
102 views191 pages

Unit 2

The document discusses Structured Query Language (SQL) and provides information about its key features and uses. SQL is a standard language for storing, manipulating, and retrieving data in relational databases and is used by all major database systems. The document covers SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, and provides examples of each. It also discusses the history and evolution of SQL over time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views191 pages

Unit 2

The document discusses Structured Query Language (SQL) and provides information about its key features and uses. SQL is a standard language for storing, manipulating, and retrieving data in relational databases and is used by all major database systems. The document covers SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, and provides examples of each. It also discusses the history and evolution of SQL over time.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 191

UNIT-2

RELATIONAL MODEL
SQL – Data definition- Queries in SQL- Updates- Views – Integrity and Security –
Relational Database design – Functional dependences and Normalization for Relational
Databases (up to BCNF).

MISSION VISION CORE VALUES


CHRIST is a nurturing ground for an individual’s Excellence and Service Faith in God | Moral Uprightness
holistic development to make effective contribution to Love of Fellow Beings
the society in a dynamic environment Social Responsibility | Pursuit of Excellence
CHRIST
Deemed to be University
SQL
● SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in a relational database.
● Designed by Donald Chamberlin and Raymond Boyce in 1974
● Forth Generation Language
● Structured – relational database is a structured database
● Query - A query is a statement requesting the retrieval of information.
● SQL can
○ query a database.
○ define the structure of the data, modify data in the database, and
○ specify security constraints.
● SQL is the standard language for Relational Database System.
● All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle,
Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.
● Also, they are using different dialects, such as −
○ MS SQL Server using T-SQL,
○ Oracle using PL/SQL,
○ MS Access version of SQL is called JET SQL (native format) etc.

Excellence and Service


CHRIST
Deemed to be University

Applications of SQL

● As mentioned before, SQL is one of the most widely used query language
over the databases. I'm going to list few of them here:
● Allows users to access data in the relational database management systems.
● Allows users to describe the data.
● Allows users to define the data in a database and manipulate that data.
● Allows to embed within other languages using SQL modules, libraries & pre-
compilers.
● Allows users to create and drop databases and tables.
● Allows users to create view, stored procedure, functions in a database.
● Allows users to set permissions on tables, procedures and views.

Excellence and Service


CHRIST
Deemed to be University

Advantages of SQL

● Open source,
● interactive language,
● high speed,
● no coding needed,
● well defined standards,
● Data portability.

Disadvantages of SQL
● Difficult Interface
● Partial Control
● Implementation
● Operating Cost

Excellence and Service


CHRIST
Deemed to be University

History of SQL
● DBMS - Implementation Language – SQL/PL - (Sequel)
● SQL - Structured Query Language – Ask – Query(Question), Tell – Answering(DB)
● Standard
○ 1960 - Network & Hierarchial - IBM
○ 1970 - Relational model - (RDBMS) (Strucutred Model)
○ 1973 – Oracle – SQl (standard) – Ingres Relational Dtabase
○ 1975 - System R – Relational Database (SQL)
○ 1979 - Oracle
○ 1982 – SQL/DS - IBM
○ 1985 – DB2 – IBM, Excel – Microsoft, Object oriented model,
○ 1986 – POSTGRES - DARPA
○ 1987 – SQL Server – Microsoft
○ 1990 – Object Relational Model
○ 1995 – MySQL – Borland, SQL Plus - Oracle (Proprietary)
○ 1996 – PostgresSQL
○ 1998 – XML – W3C (Semi Strucutred model)
○ 1999 – SQL:1999, 2000 – Developer/2000, 2003 – SQL:2003 (XML), 2006 – SQL:2006 (XML feature), 2008 – SQL:2008 (Triggers)
○ XAMPP – Php – AnyOS,Apache,Mysql,Php,Perl
○ 2010 – MySQL (freeware) – Oracle, Sybase - SAP
○ 2011 – SQL:2011
○ 2012 – MariaDB
○ 2016 – SQL:2016 (JSON features)
○ 2020 – Informix – IBM, Cloudscape – Apache
○ 2021 – SQLite – Python Library
Excellence and Service
CHRIST
Deemed to be University

SQL Query Processor

1. Parsing and translation


2. Optimization
3. Evaluation

Excellence and Service


CHRIST
Deemed to be University

1. The first step is to transform the query into a standard form.


2. A query is translated into SQL and into a relational algebraic expression. During this process, Parser
checks the syntax and verifies the relations and the attributes which are used in the query.
Example:
SELECT Ename FROM Employee
WHERE Salary > 5000;
Translated into Relational Algebra Expression
σ Salary > 5000 (π Ename (Employee))
OR
π Ename (σ Salary > 5000 (Employee))

3. The second step is Query Optimizer. In this, it transforms the query into equivalent expressions that are
more efficient to execute.

4. The third step is Query evaluation. It executes the above query execution plan and returns the result.

Excellence and Service


CHRIST
Deemed to be University

Types of SQL Commands

● DDL – Data Definition Language (create, alter, truncate, drop, rename)


● DML – Data Manipulation Language (insert, update, delete, merge)
● DCL – Data Control Language (grant, revoke)
● TCL – Transaction Control Language (commit, rollback, savepoint, set
transaction)
● DQL – Data Query Language (Select)

Excellence and Service


CHRIST
Deemed to be University

Data Definition Language (DDL)

● The SQL DDL allows specification of not only a set of relations, but also
information about each relation, including
○ The schema for each relation
○ The domain of values associated with each attribute
○ The integrity constraints
○ The set of indices to be maintained for each relation
○ The security and authorization information for each relation
○ The physical storage structure of each relation on disk

DDL or Data Definition Language actually consists of


the SQL commands that can be used to define the
database schema. It simply deals with descriptions of
the database schema and is used to create and modify
the structure of database objects in the database.

Excellence and Service


CHRIST
Deemed to be University

CREATE TABLE

● CREATE TABLE tablename


( column1 datatype(size),
column2 datatype(size),
column3 datatype(size), ....
);

Example:
● CREATE TABLE Students (ROLLNO int(3), NAME varchar(20), SUBJECT
varchar(20), );

● CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(10


0), DOB DATE);

Excellence and Service


CHRIST
Deemed to be University
ALTER TABLE
1. Adding a new column
ALTER TABLE tablename ADD columnname COLUMN-definition;
Example: ALTER TABLE STUDETAILS ADD(ADDRESS VARCHAR2(20));

2. Modify existing column


ALTER TABLE tablename MODIFY(columndefinitions....);
Example: ALTER TABLE STUDETAILS MODIFY (NAME VARCHAR2(20));

3. Dropping Column
ALTER TABLE tablename DROP COLUMN columnname;
Example: ALTER TABLE STUDETAILS DROP COLUMN ADDRESS;
3. Renaming Column
ALTER TABLE tablename RENAME COLUMN oldname TO newname;
Example: ALTER TABLE Student RENAME COLUMN NAME TO FIRSTNAME;

Excellence and Service


CHRIST
Deemed to be University

DROP TABLE
● DROP - It is used to This command deletes both the structure and record
stored in the table.

● DROP TABLE tablename;

● Example:
DROP TABLE EMPLOYEE;

Excellence and Service


CHRIST
Deemed to be University

RENAME TABLE

● ALTER TABLE tablename RENAME TO newtablename;


Example: ALTER TABLE Student RENAME TO StudentDetails;

Excellence and Service


CHRIST
Deemed to be University

TRUNCATE TABLE

● TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.

● TRUNCATE TABLE tablename;


● Example: TRUNCATE TABLE EMPLOYEE;

Excellence and Service


CHRIST
Deemed to be University

Constraints
● It is a rule to which data must conform
● Constraint names are optional
● Can be added at column level or table level
○ Table constraint – can be applied to a single column or a group of columns. This
constraint is created at the end of CREATE TABLE command or using ALTER TABLE
command
○ Column constraint – can be applied to a single column. This constraint is created using
CREATE TABLE command
● Can be enabled/disabled/dropped
● Types:
1. NOT NULL – does not accept a null value
2. UNIQUE -
3. PRIMARY KEY – NOT NULL and UNIQUE
4. CHECK
5. FOREIGN KEY
Excellence and Service
CHRIST
Deemed to be University

Super Key Super key is a set of one or more than one keys that can be used to identify a record uniquely in a
table. Example: Primary key, Unique key, Alternate key are a subset of Super Keys.
Candidate Key A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a
table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as
Primary Key.
Example: In the below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three
fields can be work as Primary Key
Primary Key Primary key is a set of one or more fields/columns of a table that uniquely identify a record in a
database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary
Key.
Alternate key An Alternate key is a key that can be work as a primary key. Basically, it is a candidate key that
currently is not a primary key.
Example: In the below diagram RollNo and EnrollNo become Alternate Keys when we define ID as
Primary Key.
Composite/Comp Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate
ound Key key, Primary key.

Unique Key A unique key is a set of one or more fields/columns of a table that uniquely identify a record in a
database table. It is like Primary key but it This key can accept only one null value and it can not
have duplicate values.

Foreign Key Foreign Key is a field in a database table that is Primary key in another table. It This key can
accept multiple null, duplicate values.
Example: We can have a DeptID column in the Employee table which is pointing to a DeptID
column in a department table where it a primary key.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

NULL/NOT NULL constraint

● Create table student(sno number(5) NULL, Name varchar2(10));


● Create table student1(sno number(5) NOT NULL, Name varchar2(10));

● alter table student modify Name varchar2(20) not null;


● alter table student modify Name varchar2(20) constraint nncnst not null;

● Note: NULL or NOT NULL cannot be defined as a table constraint. You can
have any number of NULL or NOT NULL columns in your table

Excellence and Service


CHRIST
Deemed to be University

Primary Key Constraint


● This is used to uniquely identify each row of a table.
● It never allows duplicate values for that column.
● A table can have only one primary key
● A primary key column cannot be of datatype LONG or LONG RAW
● You cannot designate a column as
○ Both primary key and foreign key
○ Both primary key and cluster key

Column Constraint:

● create table department(DeptId number primary key, Deptname varchar2(20));


Or
● create table department(DeptId number constraint pkcnst primary key, Deptname
varchar2(20));

Excellence and Service


CHRIST
Deemed to be University

TABLE CONSTRAINT:
● To define one primary key on one column
● create table department(DeptId number, Deptname varchar2(20), ClassId number,
primary key(DeptId));

● To define one primary key on 2 columns


● create table department(DeptId number, Deptname varchar2(20), ClassId number,
primary key(DeptId,ClassId));

● To add primary key to a table already created:


● Alter table department ADD primary key (DeptId);

Excellence and Service


CHRIST
Deemed to be University

Unique Constraint

● Unique is similar to primary key. Primary key column will not accept a null.
But the unique key column will accept a null vaule.

● Create table department (DeptId number(5) unique, Name varchar2(10));

Excellence and Service


CHRIST
Deemed to be University

Check constraint
● A check constraint limits the values that can be entered into one or more columns of
a database table.
● It helps to validate the column with certain conditions.

● alter table student add Gender char(1) check(Gender in ('M','F'));

● create table student(Name varchar2(20), Regnum number, Mark number(4,2),


Gender char(1) check (Gender in('M', 'F')));

● create table book(id number primary key, name varchar2(10), cc number(1), cost
number(10) check(cost > 100));

● create table book(id number primary key, name varchar2(10), cc number(1)


check(cc>=0 and cc<=4), cost number(10) check(cost > 100)); [In this table, check constraint is
given for cc column and cost column. The condition is the cc column should accept values from 1 to 4. The cost column should accept values
greater than 100. If you try to enter a value other than this you will get error]

Excellence and Service


CHRIST
Deemed to be University

Foreign key or Reference constraint


● A foreign key is a combination of columns with values based on the primary
key values from another table.
● A foreign key constraint is also known as referential integrity constraint that
establishes a relationship between the foreign key and the primary key called
the referenced key.
● The table containing the foreign key is called the child table and the table
containing the primary key is called the parent table.
● The child and parent table must be on the same database
● The foreign key and referenced key can be from same table. In this case
parent and child tables are same.
● The foreign key value in a row must appear as referenced key value in one of
the parent table’s rows.
● The value of one of the columns of foreign key must be null
● The foreign key and the

Excellence and Service


CHRIST
Deemed to be University

Table Constraint:
● create table account(account-number number primary key,branch-name
varchar2(20),balance number, foreign key(branch-name) references
branch(branch-name));
● alter table student add foreign key(DeptId) references department(DeptId);

Column constraint:
● create table course (id number primary key, rollno number references student
on delete cascade);

Excellence and Service


CHRIST
Deemed to be University

Domain Types in SQL


● char(n): A fixed-length character string with user-specified length n. The full form, character, can be used
instead.
● varchar(n): A variable-length character string with user-specified maximum length n. The full form,
character varying, is equivalent.
● int: An integer (a finite subset of the integers that is machine dependent). The full form, integer, is
equivalent.
● smallint: A small integer (a machine-dependent subset of the integer domain type).
● numeric(p, d): A fixed-point number with user-specified precision. The number consists of p digits (plus a
sign), and d of the p digits are to the right of the decimal point. Thus, numeric(3,1) allows 44.5 to be stored
exactly, but neither 444.5 or 0.32 can be stored exactly in a field of this type.
● real, double precision: Floating-point and double-precision floating-point numbers with machine-
dependent precision.
● float(n): A floating-point number, with precision of at least n digits.
● date: A calendar date containing a (four-digit) year, month, and day of the month. Eg: ’2001-04-25’
● time: The time of day, in hours, minutes, and seconds. A variant, time(p), can be used to specify the
number of fractional digits for seconds (the default being 0). It is also possible to store time zone
information along with the time. E.g: ’09:30:00’
● timestamp: A combination of date and time. A variant, timestamp(p), can be used to specify the number
of fractional digits for seconds (the default here being 6). E.g.: ’2001-04-25 10:29:01.45’

Excellence and Service


CHRIST
Deemed to be University

DML Commands

● DML commands are used to modify the database. It is responsible for all form
of changes in the database.
● The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollback.
● INSERT
● UPDATE
● DELETE
● MERGE

Excellence and Service


CHRIST
Deemed to be University

INSERT
● INSERT: The INSERT statement is a SQL query. It is used to insert data into
the row of a table.

Syntax 1:
INSERT INTO TABLE_NAME(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Syntax 2:
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN);

Syntax 3:
insert into tablename values(&col1,'&col2');
Excellence and Service
CHRIST
Deemed to be University

Examples
● To insert data into a relation, we either specify a tuple to be inserted or write a
query whose result is a set of tuples to be inserted. Obviously, the attribute
values for inserted tuples must be members of the attribute’s domain.
Similarly, tuples inserted must be of the correct arity.
● Example: Insert an account A-9732 at the Perryridge branch that has a
balance of $1200

● Or

● or

Excellence and Service


CHRIST
Deemed to be University

Examples

● Example: present a new $200 savings account as a gift to all loan customers
of the Perryridge branch, for each loan they have. Let the loan number serve
as the account number for the savings account

SQL evaluates the select statement first, giving a set of


tuples that is then inserted into the account relation.
Each tuple has a loan-number (which serves as
the account number for the new account), a branch-
name (Perryridge), and an initial balance of the new
account ($200).

Excellence and Service


CHRIST
Deemed to be University

Examples

● Example: We also need to add tuples to the depositor relation

Excellence and Service


CHRIST
Deemed to be University

DELETE

Syntax:
DELETE from tablename
WHERE condition

● The delete statement first finds all tuples t in r for which P(t) is true, and then
deletes them from r. The where clause can be omitted, in which case all
tuples in r are deleted.

● Note that a delete command operates on only one relation. If we want to


delete tuples from several relations, we must use one delete command for
each relation.

Excellence and Service


CHRIST
Deemed to be University

Example
● Example: To delete all tuples from the loan relation

● Example: Delete all account tuples in the Perryridge branch.

● Example: Delete all loans with loan amounts between $1300 and $1500.

● Example: Delete all account tuples at every branch located in Needham


This delete request first finds
all branches in Needham,
and then deletes all account
tuples pertaining to those
branches.

Excellence and Service


CHRIST
Deemed to be University

Example

● Example: delete the records of all accounts with balances below the average
at the bank

Excellence and Service


CHRIST
Deemed to be University

UPDATE

Syntax:
UPDATE tablename
SET [column_name1= value1,...columnnameN = valueN]
[WHERE CONDITION]

Excellence and Service


CHRIST
Deemed to be University

Example

● Example: Pay 5 percent interest on accounts to all balances

● Example: Pay 5 percent interest on accounts with a balance of $1000 or more

● Example: Pay 5 percent interest on accounts whose balance is greater than


average

Excellence and Service


CHRIST
Deemed to be University

Example

● Example: If all accounts with balances over $10,000 receive 6 percent


interest, whereas all others receive 5 percent

the order of the two


update statements is
important.

Excellence and Service


CHRIST
Deemed to be University

MERGE

1 merge into stud c


2 using student s
3 on (s.Regnum = c.Regnum)
4 when matched then
5 update set
6 c.Gender = s.Gender,
7 c.Name = s.Name
8 when not matched then
9 insert values(s.Name,s.Gender,s.Regnum);

Excellence and Service


CHRIST
Deemed to be University

DQL Commands

● The select clause corresponds to the projection operation of the relational


algebra. It is used to list the attributes desired in the result of a query.

● The from clause corresponds to the Cartesian-product operation of the


relational algebra. It lists the relations to be scanned in the evaluation of the
expression.

● The where clause corresponds to the selection predicate of the relational


algebra. It consists of a predicate involving attributes of the relations that
appear in the from clause.

Excellence and Service


CHRIST
Deemed to be University

● A typical SQL query has the form

● Each Ai represents an attribute or column, and each ri a relation or table. P is


a predicate (condition).

Excellence and Service


CHRIST
Deemed to be University

The select Clause

● Example: Find the names of all branches in the loan relation

● To remove duplicates, distinct is used:

● The keyword all to specify explicitly that duplicates are not removed:

Excellence and Service


CHRIST
Deemed to be University

The where Clause

● Example: Find all loan numbers for loans made at the Perryridge branch with
loan amounts greater that $1200 SQL uses the logical
connectives and, or, and
not—rather than the
mathematical symbols ∧,
∨, and ¬ —in the where
clause.

● Example: Find the loan number of those loans with loan amounts between
$90,000 and $100,000

Excellence and Service


CHRIST
Deemed to be University

The from Clause

● Example: For all customers who have a loan from the bank, find their names,
loan numbers and loan amount.

● Example: Find the customer names, loan numbers, and loan amounts for all
loans at the Perryridge branch

Excellence and Service


CHRIST
Deemed to be University

Operators, Functions,
Expressions and
Conditions

Excellence and Service


CHRIST
Deemed to be University

Operators

● Arithmetic operators
● Character operators
● Comparison operators
● Logical operators
● Set operators

Excellence and Service


CHRIST
Deemed to be University

Arithmetic operators

● Select * from student where m1+m2+m3>200;


● select 35*4 product from dual;

Character Operators
select customer_city || customer_street from customer; // concatenation

Excellence and Service


CHRIST
Deemed to be University

Comparison operators
● select * from loan where amount = 1300;
● select * from loan where amount != 1300;
● select * from loan where amount <> 1300;
● select * from loan where amount > 1300;
● select * from loan where amount < 1300;
● select * from customer where customer_street in ('Main','Park');
● select * from customer where customer_street not in ('Main','Park');
● select * from loan where amount = some (500,1000,1500);
● select * from loan where amount = any (500,1000,1500);
● select * from loan where amount = all (500,1000,1500);
● select * from loan where amount between 500 and 1500;
● select * from customer where customer_name like 'S%';
● select * from customer where customer_name not like '%s';
● select * from account where balance is null;
● select * from account where balance is not null;

Excellence and Service


CHRIST
Deemed to be University

Logical Operators

● select * from account where not(balance is null);


● select * from account where balance >500 and balance <1500;
● select * from account where balance >500 or balance <1500;

Excellence and Service


CHRIST
Deemed to be University

Set Operations

● union, intersect, and minus operations


● The relations participating in the operations must be compatible; that is, they
must have the same set of attributes.

Excellence and Service


CHRIST
Deemed to be University

The Union Operation

● combines the results of two queries


● Example: To find all customers having a loan, an account, or both at the bank
The union operation
automatically eliminates
duplicates, unlike the
select clause.

● To retain all duplicates, write union all in place of union

Excellence and Service


CHRIST
Deemed to be University

The Intersect Operation

● returns only those rows returned by both queries


● Example: To find all customers who have both a loan and an account at the
bank

The intersect operation


automatically eliminates
duplicates.

Excellence and Service


CHRIST
Deemed to be University

The Minus Operation

● returns only unique rows returned by the first query that are not in second

● Example: To find all customers who have an account but no loan at the bank

select customer_name from depositor minus select


customer_name from borrower;

Excellence and Service


CHRIST
Deemed to be University

Functions

● Single row (or scalar) functions


○ Number
○ Character
○ Date
○ Conversion
○ General
● Group (or aggregate) functions

Excellence and Service


CHRIST
Deemed to be University

Number functions
● select abs(-15) Absolute from dual;
● select ceil(7.1) ceil from dual; //
● select floor(7.6) ceil from dual;
● select cos(3) cosine_value from dual;
● select exp(4) EXP from dual;
● select mod(5,10) Modulus from dual;
● select round(15.6789,2) round from dual;
● select trunc(15.791,2) TRUNCATE from dual;
● select sign(-15) sign from dual;
● select sin(3) sin from dual;
● select tan(3) TAN from dual;
● select sqrt(3) SQRT from dual;
● select VSIZE('dbms') VSIZE from dual;

● Dual is a table automatically created by oracle db.


Excellence and Service
CHRIST
Deemed to be University

Character Functions
● select chr(67)||chr(65)||chr(84) from dual;
● select concat(customer_street,customer_city) from customer;
● select initcap('christ') from dual;
● select lower(customer_street) from customer;
● select upper(customer_street) from customer;
● select lpad(customer_street,9,customer_city) from customer; // returns char 1 left padded to
length n
● select rpad(customer_street,9,customer_city) from customer; // returns char 1 right padded to
length n
● select ltrim('welcome','we') from dual;
● select rtrim('welcome','me') from dual;
● Select translate(‘BREEZE’ , ‘AER’,’124’) TRANSLATE from dual;
● select branch_name from branch where soundex(branch_name) = soundex('Dounton'); ----
returns a character string that that the phonetic representation of char.
● select substr('DBMS',3) from dual;
● select ASCII('E') from dual;
● select instr('welcome','e',2,2) from dual; --searches char1 beginning with its nth character for
mth occurrence of char2
● select length('welccc444e') from dual;

Excellence and Service


CHRIST
Deemed to be University

Date Functions

● Default date: ‘DD-MM-YY’


● Example: 12-APR-03
● select sysdate from dual;
● select to_char(sysdate,'MM-DD-YY hh: mi: ss') now from dual;
● select add_months(sysdate,5) mon from dual;
● select months_between('05-oct-1984',sysdate) mon from dual;
● select name, dob, months_between(sysdate,dob) mbt from student;
● select last_day(sysdate) from dual;
● select last_day(sysdate),last_day(sysdate)-sysdate daysleft from dual;
● select next_day(sysdate,'monday') from dual;
● SQL> select to_char(sysdate,'MONTH,DD,YYYY') today from dual;
● select to_date('09-15-21','MM/DD/YYYY') today from dual;
● select round(to_date('15-JUL-21'),'year') from dual;
● select trunc(to_date('17-JUL-21'),'month') from dual;

Excellence and Service


CHRIST
Deemed to be University

Date Formats

MM - select to_char(sysdate, 'DD,MM,YY') from dual; //number


RM - select to_char(sysdate, 'DD,RM,YY') from dual; // roman numerals
MON - select to_char(‘09-04-21’, 'MON,DD,YY') from dual; //3 letter abbre
MONTH - select to_char(sysdate, 'DD,MONTH,YY') from dual; //month
fully spelt
DDD - select to_char(sysdate, 'DDD,MM,YY') from dual;
DD - select to_char(sysdate, 'DD,MM,YY') from dual;// no. of days in a
month
YYYY - select to_char(sysdate, 'DY,Month,YYYY') from dual; //full 4 digit
year

Excellence and Service


CHRIST
Deemed to be University
General functions
● NVL - select nvl(null,sysdate) from dual;
● NVL2 - select nvl2('19-SEP-21',sysdate,'18-SEP-21') from dual;
● NULLIF - select nullif('19-SEP-21','18-SEP-21') from dual;
● COALESCE - select coalesce(null,null,6,7,10,null) from dual;

Function Description
NVL (expr1, expr2) Converts a null value to an actual value. You can use the NVL function to
convert any data type, but the return value is always the same as the data type
of expr1.
NVL2(expr1, expr2, If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3.
expr3) The argument expr1 can have any data type. The expr2 and expr3 can have any data
types except LONG. If the data types of expr2 and expr3 are different, the
Oracle server converts expr3 to the data type of expr2 before comparing them
unless expr3 is a null constant.
NULLIF (expr1, Compares two expressions and returns null if they are equal; returns the first
expr2) expression if they are not equal
COALESCE (expr1, Returns the first non-null expression in the expression list. COALESCE function
expr2, ... exprn) can take multiple alternate values

Excellence and Service


CHRIST
Deemed to be University

Conditional Expressions

● CASE
○ IF-THEN-ELSE statement

CASE expr WHEN comparison_expr1 THEN return_expr1


[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END

select account_number, balance,


CASE branch_name WHEN 'Downtown' THEN balance+500
WHEN 'Perryridge' THEN balance+1000
ELSE balance
END bal
from account;

Excellence and Service


CHRIST
Deemed to be University

● DECODE
○ IF-THEN-ELSE statement

DECODE(col|expression, search1, result1[, search2, result2,...,][, default])

select account_number, balance,


DECODE(branch_name, 'Downtwn', balance+500, 'Perryrdge', balance+1000,
'Mianus', balance-100,balance)
bal
from account;

Excellence and Service


CHRIST
Deemed to be University

● select greatest('HARRY','HAI') from dual; //HAPPY


● select least('HARRY','HAI') from dual; //HAI

Excellence and Service


CHRIST
Deemed to be University

Conversion Functions

To_CHAR

● TO_CHAR(number, 'format_model')
● Example: select to_char(sysdate,'dd-mm-yyyy')
from dual;

● Default: dd-mon-yy

Excellence and Service


CHRIST
Deemed to be University

● Convert a character string to a number format


● TO_NUMBER(char[, 'format_model'])
● Example:
SELECT to_number('56,789,453','999,999,999') from
dual;
SELECT TO_NUMBER('$65.169', 'L99.999') from dual;
Element Result
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as thousands indicator

● Convert a character string to a date format


● TO_DATE(char[, 'format_model'])
● Example: select TO_DATE('01-Jan-90','DD-Mon-RR')
from dual;

Excellence and Service


CHRIST
Deemed to be University

Nested Functions

SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8),'_US'))
FROM employees
WHERE department_id = 60;

Excellence and Service


CHRIST
Deemed to be University

SQL Aggregate Functions


● Aggregate functions are functions that take a collection (a set or multiset) of
values as input and return a single value. SQL offers five built-in aggregate
functions:
1. Average: avg
2. Minimum: min
3. Maximum: max
4. Total: sum
5. Count: count
6. Distinct
7. Variance - select variance(amount) from loan;
8. Stddev - select stddev(amount) from loan;
● The input to sum and avg must be a collection of numbers, but the other
operators can operate on collections of nonnumeric data types, such as
strings, as well.
Excellence and Service
CHRIST
Deemed to be University
avg
● Example: Find the average account balance at the Perryridge branch.

Tuples with the same


value on all attributes in
the group by clause are
placed in one group.
● Example: Find the average account balance at each branch

● Example: Select those branches where the average account balance is more than $1200.

● Example: Find the average balance for all accounts

Excellence and Service


CHRIST
Deemed to be University

count

● Example: Find the number of depositors for each branch

● Example: To find the number of tuples in the customer relation

SQL does not allow the use of


distinct with count(*). It is
legal to use distinct with
max and min, even though the
result does not change.

Excellence and Service


CHRIST
Deemed to be University

Min and max

● Example: find the maximum across all branches of the total balance at each
branch

Excellence and Service


CHRIST
Deemed to be University

sum

● Example: total all loan amounts

All aggregate functions except count(*) ignore null values in their input collection. The
count of an empty collection is defined to be 0, and all other aggregate operations
return a value of null when applied on an empty collection. The effect of null values on
some of the more complicated SQL constructs can be subtle.

Excellence and Service


CHRIST
Deemed to be University

Grouping Things Together

● Group by
● Order by
● Where
● Having

● Group by and having follows where

Excellence and Service


CHRIST
Deemed to be University

Group by

● Find the average loan amount for each customer who lives in "Downtown"
and has at least two loans

select customer_name,avg(amount)
from loan,borrower
where loan.loan_number = borrower.loan_number and
branch_name='Downtown'
group by customer_name
having count(customer_name)>=2;

Excellence and Service


CHRIST
Deemed to be University

Order by
● The order by clause causes the tuples in the result of a query to appear in
sorted order.
● Example: List in alphabetic order all customers who have a loan at the
Perryridge branch

● By default, the order by clause lists items in ascending order. To specify the
sort order, specify desc for descending order or asc for ascending order.

● Example: list the entire loan relation in descending order of amount.

Excellence and Service


CHRIST
Deemed to be University

Having Clause

● Example: Find the branch that has the highest average balance
As it does for some, SQL also allows
< all, <= all, >= all, = all, and <> all
comparisons. As an exercise, verify
that <> all is identical to not in.

Aggregate functions cannot be composed in SQL. Thus,


we cannot use max (avg (. . .)). Instead, we can follow
this strategy: We begin by writing a query to find all
average balances, and then nest it as a subquery of a
larger query that finds those branches for which the
average balance is greater than or equal to all average
balances:

Excellence and Service


CHRIST
Deemed to be University

where

● Example: Find the average balance for each customer who lives in Harrison
and has at least three accounts

• If a where clause and a having clause appear in the same query, SQL applies the predicate in the
where clause first.

• Tuples satisfying the where predicate are then placed into groups by the group by clause.

• SQL then applies the having clause, if it is present, to each group; it removes the groups that do not
satisfy the having clause predicate.

• The select clause uses the remaining groups to generate tuples of the result of the query.

Excellence and Service


CHRIST
Deemed to be University

String Operations
● SQL specifies strings by enclosing them in single quotes. A single quote character
that is part of a string can be specified by using two single quote characters; for
example the string “It’s right” can be specified by ’It”s right’.
● The most commonly used operation on strings is pattern matching using the operator
like. Patterns are described using two special characters:
○ Percent (%): The % character matches any substring.
○ Underscore ( ): The character matches any character.
● Patterns are case sensitive; that is, uppercase characters do not match lowercase
characters, or vice versa.
● Examples:
○ ’Perry%’ matches any string beginning with “Perry”.
○ ’%idge%’ matches any string containing “idge” as a substring, for example,
○ ’Perryridge’, ’Rock Ridge’, ’Mianus Bridge’, and ’Ridgeway’.
○ ’ ’ matches any string of exactly three characters.
○ ’ %’ matches any string of at least three characters.

Excellence and Service


CHRIST
Deemed to be University

● Example: Find the names of all customers whose street address includes the
substring ‘Main’.

like ’ab \%cd%’ escape ’\’ matches all strings beginning with
“ab%cd”.
like ’ab\\cd%’ escape ’\’ matches all strings beginning with
“ab\cd”.

● SQL allows to search for mismatches instead of matches by using the not
like comparison operator.

Excellence and Service


CHRIST
Deemed to be University

JOIN Operation
● The SQL Joins clause is used to combine records from two or more tables in
a database. A JOIN is a means for combining fields from two tables by using
values common to each.
Types of Join
1. INNER JOIN − returns rows when there is a match in both tables.
2. LEFT OUTER JOIN − returns all rows from the left table, even if there are no
matches in the right table.
3. RIGHT OUTER JOIN − returns all rows from the right table, even if there are
no matches in the left table.
4. FULL OUTER JOIN − returns rows when there is a match in one of the
tables.
5. SELF JOIN − is used to join a table to itself as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
6. CARTESIAN JOIN − returns the Cartesian product of the sets of records
from the two or more joined tables.
Excellence and Service
CHRIST
Deemed to be University
Consider the following two tables −
Table 1 − CUSTOMERS Table
+----+----------+-----+-----------+----------+ Now, let us join these two tables in our SELECT statement
| ID | NAME | AGE | ADDRESS | SALARY | as shown below.
+----+----------+-----+-----------+----------+ SELECT ID, NAME, AGE, AMOUNT
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | FROM CUSTOMERS, ORDERS
| 2 | Khilan | 25 | Delhi | 1500.00 | WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
This would produce the following result.
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+--------+
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | AMOUNT |
Table 2 − ORDERS Table
+----+----------+-----+--------+
+-----+---------------------+-------------+--------+
| 3 | kaushik | 23 | 3000 |
|OID | DATE | CUSTOMER_ID | AMOUNT |
| 3 | kaushik | 23 | 1500 |
+-----+---------------------+-------------+--------+
| 2 | Khilan | 25 | 1560 |
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 4 | Chaitali | 25 | 2060 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
+----+----------+-----+--------+
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables,
such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most
common operator is the equal to symbol.

Excellence and Service


CHRIST
Deemed to be University

INNER JOIN

● The INNER JOIN creates a new result table by combining column


values of two tables (table1 and table2) based upon the join-
predicate. The query compares each row of table1 with each row of
table2 to find all pairs of rows which satisfy the join-predicate. When
the join-predicate is satisfied, column values for each matched pair
of rows of A and B are combined into a result row.

Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;

Excellence and Service


CHRIST
Deemed to be University

LEFT OUTER JOIN

● This means that a left join returns all the values from the left table,
plus matched values from the right table or NULL in case of no
matching join predicate.

● Syntax
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;

Excellence and Service


CHRIST
Deemed to be University

RIGHT OUTER JOIN

● right join returns all the values from the right table, plus matched
values from the left table or NULL in case of no matching join
predicate.
● Syntax:
SELECT table1.column1, table2.column2...
FROM table1 RIGHT
JOIN table2
ON table1.common_field = table2.common_field;

Excellence and Service


CHRIST
Deemed to be University

FULL JOIN

● The SQL FULL JOIN combines the results of both left and right outer
joins.
● The joined table will contain all records from both the tables and fill
in NULLs for missing matches on either side.
● Syntax
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;

Excellence and Service


CHRIST
Deemed to be University

SELF JOIN

● The SQL SELF JOIN is used to join a table to itself as if the table were
two tables; temporarily renaming at least one table in the SQL
statement.
● Syntax
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;

Excellence and Service


CHRIST
Deemed to be University

CARTESIAN JOIN

● The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the
sets of records from two or more joined tables. Thus, it equates to an inner
join where the join-condition always evaluates to either True or where the
join-condition is absent from the statement.
● Syntax
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]

Excellence and Service


CHRIST
Deemed to be University

SUBQUERIES

● Naming of queries one within the other is called a subquery


● Subqueries are executed from most deeply nested to the
least deeply nested
● Can be used for select, update, insert and delete statement

● Single row subquery


● Multiple row subquery
● Correlated subquery

Excellence and Service


CHRIST
Deemed to be University

● Example: Single Row Subquery


○ select loan_number from loan where branch_name = (select branch_name from
branch where branch_name = 'Redwood');
○ select loan_number from loan where branch_name = (select branch_name from
branch where assets = 9000000);
○ update branch set assets = 7200000 where branch_name = (select branch_name
from branch where branch_name='Brighton');
○ update account set balance = (select balance+500 as bal from account where
account_number = 'A-101') where account_number = 'A-101';
● Example: Multiple Row Subquery
o select loan_number from loan where amount >some (select amount from loan
where amount>500);
o Frame 4 more multiple row subqueries (some, all, exists, any)
● Correlated Subquery:
o select L.loan_number from loan L where L.amount = (select avg(amount) from
loan where L.loan_number = loan_number);
o 4 more example queries

Excellence and Service


CHRIST
Deemed to be University

Special Operations with Subqueries

● A subquery is a select-from-where expression that is nested within another


query.
● A common use of subqueries is to perform tests for
○ set membership,
○ make set comparisons, and

Excellence and Service


CHRIST
Deemed to be University

Set Membership
● The in connective tests for set membership, where the set is a collection of
values produced by a select clause.
● The not in connective tests for the absence of set membership.
● Example: Find all customers who have both a loan and an account at the
bank

● Find all customers who have both an account and a loan at the Perryridge
branch

Excellence and Service


CHRIST
Deemed to be University

● Example: find all customers who do have a loan at the bank, but do not have
an account at the bank

The in and not in


operators can also be
used on enumerated
sets.

● Example: selects the names of customers who have a loan at the bank, and
whose names are neither Smith nor Jones

Excellence and Service


CHRIST
Deemed to be University

Set Comparison

● Example: Find the names of all branches that have assets greater than those
of at least one branch located in Brooklyn.
The phrase “greater than at least one”
is represented in SQL by > some.

● Example: find the names of all branches that have an asset value greater
than that of each branch in Brooklyn

The construct > all corresponds to


the phrase “greater than all.”

Excellence and Service


CHRIST
Deemed to be University

Test for Empty Relations

● The exists construct returns the value true if the argument subquery is
nonempty
● Example: Find all customers who have both an account and a loan at the
bank

Excellence and Service


CHRIST
Deemed to be University

● Example: Find all customers who have an account at all the branches located
in Brooklyn
We can write “relation A
contains relation B” as “not
exists (B except A).”

Excellence and Service


CHRIST
Deemed to be University

Null Values

● SQL allows the use of null values to indicate absence of information about the
value of an attribute.
● Example: to find all loan numbers that appear in the loan relation with null
values for amount:

● The predicate is not null tests for the absence of a null value

Excellence and Service


CHRIST
Deemed to be University

Test for the Absence of Duplicate Tuples

● The unique construct returns the value true if the argument subquery
contains no duplicate tuples.
● Example: Find all customers who have at most one account at the Perryridge
branch

Excellence and Service


CHRIST
Deemed to be University

● Example: Find all customers who have at least two accounts at the Perryridge
branch

select unique customer_name Formally, the unique test on a relation is defined to fail
from borrower if and only if the relation
where exists (select * contains two tuples t1 and t2 such that t1 = t2. Since
from depositor the test t1 = t2 fails if any of the
where depositor.customer_name = fields of t1 or t2 are null, it is possible for unique to be
borrower.customer_name); true even if there are multiple
copies of a tuple, as long as at least one of the
attributes of the tuple is null.

Excellence and Service


CHRIST
Deemed to be University

The Rename Operation

● SQL provides a mechanism for renaming both relations and attributes.

● The as clause can appear in both the select and from clauses.

Excellence and Service


CHRIST
Deemed to be University

Renaming Table name

● Tuple variables are defined in the from clause by way of the as clause.
● Example: For all customers who have a loan from the bank, find their names,
loan numbers, and loan amount
select customer_name, T.loan_number, S.amount
from borrower T, loan S
where T.loan_number = S.loan_number;

● Example: Find the names of all branches that have assets greater than at
least one branch located in Brooklyn

Excellence and Service


CHRIST
Deemed to be University

Views
● View is a virtual table that has columns similar to a table.
● It is a database object that is a logical representation of a table.
● Has no storage of its own.
● Provides restricted access to data
● Contains a SQL select statement
● A create view clause creates a view definition in the database, and the view definition stays in
the database until a command drop view view-name is executed.
CREATE VIEW view_name AS
SELECT columns
FROM tables
WHERE conditions;
● The view name is represented by v.
● Example: consider the view consisting of branch names and the names of customers who
have either an account or a loan at that branch.

Excellence and Service


CHRIST
Deemed to be University

● Using the view all-customer, we can find all customers of the Perryridge
branch

● A table cannot be updated using views if the select query contains a column
with the following:
○ DISTINCT keyword
○ Group function
○ Group by clause
○ Expressions
○ NOT NULL Column excluded

Excellence and Service


CHRIST
Deemed to be University

SYNONYM

● Synonym is an alternative name for a table, view, sequence, procedure,


stored function, package, snapshop or another synonym.
● It is a name assigned to a table or view that may thereafter be used to refer it.

● Syntax:
● Create [public] synonym <synonym name> for <table name>

● Used for security and convenience.


● Can be used with thw following DML statements:
○ Select
○ Insert
○ Update
○ delete

Excellence and Service


CHRIST
Deemed to be University

Working with synonyms

● create synonym brsyn for branch;


● insert into brsyn values('Kengeri','Bangalore',300000);
● update brsyn set branch_city = 'Bengaluru' where branch_name = 'Kengeri';
● delete from brsyn where branch_name = 'Kengeri';
● drop synonym brsyn;

Excellence and Service


CHRIST
Deemed to be University

INDEXES
● Used to speed execution and imposes uniqueness upon certain data
● Ensure speedy retrieval of data
● used when
○ Searching for rows with specified index column values
○ Accessing tables in index column order
● Created on columns
● Improves query performance but slow updates and deletes
● Requires storage space for creating index
● A foreign key can be indexed to process join faster
● Always created in ascending order
● For primary key and unique constraint, index is automatically created.

Excellence and Service


CHRIST
Deemed to be University

● Syntax:
● Create [unique] index <index name> on <tablename> (<field name>) cluster
<cluster name);

● Example:
○ create index indemp on emp(eno);
○ create unique index indemp on emp(eno);

● Unique indexes – each row of the indexed table has unique value
● Nonunique indexes – each row’s indexed values can repeat

● drop index indemp;

Excellence and Service


CHRIST
Deemed to be University

Clusters

● Clustering is a method of storing related tables in a location by its key value


● A cluster is a schema object that contains one or more tables that all have
one or more columns in common.
● Cluster key is the column by which the tables are joined in the query

● Used to reduce the time and space of accessing and storing tables.
● Types of clusters:
○ Index clusters – hold data from 2 or more tables in the same oracle blocks. A cluster
must be created and an index must be created
○ Hash clusters – holds data and its key values using a hash algorithm

Excellence and Service


CHRIST
Deemed to be University

● Syntax:
● Create cluster <cluster name> (column_name datatype)

● create cluster Jon(loan_number number); //cluster id created


● create table Jon1(loan_number number primary key, branch_name varchar2(10)) cluster
Jon(loan_number);
● create table Jon2(loan_number number references Jon1 on delete cascade, name
varchar2(10),id number primary key) cluster Jon(loan_number);

Creating Cluster Indexes:


● To insert records on Jon1 and Jon2 we have to first create a cluster index on the cluster Jon
● Syntax: create index I_Jon on cluster Jon; // cluster index is created on cluster id
Retrieving data through Cluster Index:
select * from Jon1 J1,Jon2 J2 where J1.loan_number = J2.loan_number; // Here loan_number acts
as cluster index

drop cluster classs including tables cascade constraints;

Excellence and Service


CHRIST
Deemed to be University

SEQUENCE

● A sequence is a database object that can be used to provide quick


generation of unique numbers.
● Helps multiple users to generate unique integers
● Rollback statement will not rollback a sequence.
● Syntax: Sequence_name: Name of the sequence.

initial_value: starting value from where the sequence starts.


CREATE SEQUENCE sequence_name Initial_value should be greater than or equal to minimum value and less
than equal to maximum value.
START WITH initial_value
increment_value: Value by which sequence will increment itself.
INCREMENT BY increment_value Increment_value can be positive or negative.

MINVALUE minimum value minimum_value: Minimum value of the sequence.


maximum_value: Maximum value of the sequence.

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

CYCLE|NOCYCLE ; nocycle: An exception will be thrown if sequence exceeds its max_value.

ORDER|NOORDER ORDER: guarantees that sequence numbers are generated in order of


request.

NOORDER: does not guarantees that sequence numbers are generated


in order of request.

Excellence and Service


CHRIST
Deemed to be University

● create sequence s_Jon1 start with 1 increment by 2 minvalue 0


maxvalue 100 cycle;

● insert into Jon1 values(s_Jon.nextval,'kerala',1); // sequence is used


in the insert statement. Loan_number is generated automatically.

Alter Sequence:
ALTER SEQUENCE sequence_name
INCREMENT BY increment_value
MINVALUE minimum value
Example:
MAXVALUE maximum value
alter sequence s_Jon increment by 2 MAXVALUE 25
CYCLE|NOCYCLE ; NOCYCLE;
ORDER|NOORDER

Drop Sequence:
drop sequence s_Jon;
Excellence and Service
CHRIST
Deemed to be University

Complex Queries

● two ways to express a complex query:


○ derived relations and
○ the with clause.

Excellence and Service


CHRIST
Deemed to be University

Derived Relations

● Example: find the maximum across all branches of the total balance at each
branch

Excellence and Service


CHRIST
Deemed to be University

The with Clause

● The with clause provides a way of defining a temporary view whose definition
is available only to the query in which the with clause occurs.
● Example: select accounts with the maximum balance; if there are many
accounts with the same maximum balance, then select all of them.
WITH temporaryTable (averageValue) as
(SELECT avg(Attr1)
FROM Table)
SELECT Attr1
FROM Table, temporaryTable
WHERE Table.Attr1 >
temporaryTable.averageValue;

Excellence and Service


CHRIST
Deemed to be University

● Example: For example, suppose we want to find all branches where the total
account deposit is less than the average of the total account deposits at all
branches.

Excellence and Service


CHRIST
Deemed to be University

SQL Functions

● Character function
● Number Function
● Date Function
● Conversion function
● General function

Excellence and Service


CHRIST
Deemed to be University

DCL Commands
● Grant - The grant statement is used to confer authorization.

● Example 1: To grant users U1, U2, and U3 select authorization on the


account relation:

● Example: To give users U1, U2, andU3 update authorization on the amount
attribute of the loan relation:

● Example: To allow user U1 to create relations that reference the key branch-
name of the branch relation as a foreign key:

Excellence and Service


CHRIST
Deemed to be University

Creating users

● create user Jon identified by jon;


● Disc

● conn jon;
● Enter password:

● ERROR:
● ORA-01045: user JON lacks CREATE SESSION privilege; logon denied

Excellence and Service


CHRIST
Deemed to be University

● Example: if we wish to allow U1 the select privilege on branch and allow U1


to grant this privilege to others, we write

Excellence and Service


CHRIST
Deemed to be University

● Revoke: To revoke an authorization, we use the revoke statement.

● Example: to revoke the privileges that we granted previously

Excellence and Service


CHRIST
Deemed to be University

● Example: revokes only the grant option

● Example: the system returns an error if there are any cascading revokes, and
does not carry out the revoke action.

Excellence and Service


CHRIST
Deemed to be University

TCL Commands

● COMMIT Statement -- commit (make persistent) all changes for the current
transaction
● ROLLBACK Statement -- roll back (rescind) all changes for the current
transaction

Excellence and Service


CHRIST
Deemed to be University
SIMPLE REPORTS
Command Explanation Example
remark Tells SQLPLUS to treat the words as comments remark select * from customer;
TTITLE Sets the top title for each page of the report TTITLE center 'customer details'
BTITLE Sets the bottom title for each page of the report BTITLE left 'customer_details';
select * from customer;
COLUMN Helps to format the column. COLUMN customer_name FORMAT A25 HEADING
'EMPLOYEE|NAME‘
select * from customer;
Set headsep Header separator splits a title into 2 or more lines
Compute sum Helps to calculate subtotals. Every compute sum must
have a related break on.
spool
Set line size Sets the maximum number of characters allowed on any
line of the report
Break on Every break on must have a related order by
Set page size Sets the maximum number of lines per page
Set new page Sets the number of blank lines between pages
Spool Moves the report on the screen into a file to be printed
/* */ Beginning and end of a comment. Similar to remark
-- Beginning and end of an inline comment. Similar to
remark
Set pause Makes screen display stop between pages of display
Save Saves the sql query into a file
Host Sends any command to the host operating system
Start To execute the instructions that is saved ina file
Edit Opens the editor Excellence and Service
CHRIST
Deemed to be University

Example

REM stude STUDENT INFORMATION


REM STUDENT MARK DETAILS
SET HEADSEP _
ttitle left 'STUDENT MARK DETAILS' skip 1-
center '==================' skip 2;
btitle 'Report Over'
column ser_no heading 'ser_num'
column student_name heading 'stud_name' format A10
column total heading 'TOT' format 999.9
break on student_name skip 2;
--compute sum label 'overallmarks' of total average_mark on
student_name;
select * from stude;

Excellence and Service


CHRIST
Deemed to be University

PL/SQL
● PL/SQL is Oracle’s Procedural language superset of SQL
● Helps to code the business rules, trigger database events to occur, to add
programming logic for executing SQL commands.
● PL/SQL code is grouped into structure called blocks
● Each blocks are named – named blocks
● Not named blocks – anonymous blocks
● PL/SQL blocks consists of several sections:
○ Declaration Section
■ Declare
○ Executable command section
■ Begin
○ Exception handling section
■ Exception
■ End

Excellence and Service


CHRIST
Deemed to be University

Structure of PL/SQL Block

Declare
<Declaration Section>
Begin
<Executable Commands>
Exception
<Exception Handling>
End;

Excellence and Service


CHRIST
Deemed to be University

Declaration Section

● To declare variables, constants, nested tables, variable-size arrays,


records, VARRAY and record composite datatype.

● Examples:
○ tax := price * tax_rate;
○ bonus := current_salary * 0.10;
○ amount := to_number(substr(‘750 dollars’,1,3));
○ valid := false;
○ Select sal * 0.10 into bonus from emp where empno = 101;
○ Credit_limit constant real := 5000.00;

Excellence and Service


CHRIST
Deemed to be University

Cursor
● Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by
Database Server at the Time of Performing DML operations on Table by User.
Cursors are used to store Database Tables.
● Two kinds of cursors
○ Implicit – queries that return one row, cursor is implicitly declared
○ Explicit - queries that return more than one row, cursor is explicitly declared
● Cursor is declared in the declaration section
● Result set is the set of rows returned by a multi-row query.
● An explicit cursor points to the current row in the result set.
● PL/SQL program opens a cursor, processes rows returned by a query, closes the
cursor. Just like a file pointer marks the current position in an open file, cursor marks
the current position in the resultset.
● To control a cursor – open, fetch, close statements
● %rowtype – It is an attribute that represents a row in a table of type record
○ Used for declaring variables

Excellence and Service


CHRIST
Deemed to be University

● Declaring a cursor:
● Syntax: CURSOR cursor_name IS select_statement;
● Example: CURSOR c_customers IS SELECT id, name, address FROM
customers;

● Opening a cursor
● Syntax: OPEN c_customers; // allocates memory

● Fetching the Cursor


● FETCH c_customers INTO c_id, c_name, c_addr; // row-wise data

● Closing the Cursor: CLOSE c_customers; //deallocates memory

Excellence and Service


CHRIST
Deemed to be University

Example: Method 1
declare
ns constant number(2) := 2;
mtotal number;
maverage number(6,2);
mrem varchar2(5);
cursor c1 is select * from stud_mark;
x c1%rowtype;
begin
for x in c1 loop
mtotal := x.mark1 + x.mark2;
maverage := mtotal / ns;
if maverage >= 35 then mrem := 'PASS';
else
mrem := 'FAIL';
end if;
update stud_mark set total = mtotal, average = maverage, rem = mrem where sno = x.sno;
end loop
commit;
end;

Excellence and Service


CHRIST
Deemed to be University

Example: Method 2
declare
ns constant number(2) := 2;
mtotal number;
maverage number(6,2);
mrem varchar2(5);

cursor c1 is select * from stud_mark;


x c1%rowtype;

begin

for x in c1 loop

mtotal := x.mark1 + x.mark2;


maverage := mtotal / ns;

if maverage >= 35 then mrem := 'PASS';


else
mrem := 'FAIL';
end if;

update stud_mark set total = mtotal, average = maverage, rem = mrem where sno = x.sno;

end loop
commit;

open c1;
dbms_output.put_line('===============================================================');
dbms_output.put_line('sno sname');
dbms_output.put_line('===============================================================');
loop
fetch c1 into x;
exit when c1%notfound;

dbms_output.put_line(x.sno||' '||x.sname||' '||x.mark1||' '||x.mark2||' '||x.total||' '||x.average||' '||x.rem);


Excellence and Service
CHRIST
Deemed to be University

Functional dependences and Normalization for Relational


Databases (up to BCNF).
● Functional dependency is a constraint that specifies the relationship between two sets of attributes of a
table dependent on each other where one set can accurately determine the value of other sets.

● Introduced by E. F. Codd, it helps in preventing data redundancy and gets to know about bad designs.

● To understand the concept thoroughly, let us consider P is a relation with attributes X and Y. Functional
Dependency is represented by -> (arrow sign)

● It is denoted as X → Y, where X is a set of attributes that is capable of determining the value of Y. The
attribute set on the left side of the arrow, X is called Determinant, while on the right side, Y is called
the Dependent.

Excellence and Service


CHRIST
Deemed to be University
Example
● We have a <Department> table with two attributes − DeptId and DeptName.
○ DeptId = Department ID
○ DeptName = Department Name

● The DeptId is our primary key. Here, DeptId uniquely identifies the DeptName
attribute. This is because if you want to know the department name, then at first you
need to have the DeptId.
DeptId DeptName
001 Finance
002 Marketing
003 HR

● Therefore, the above functional dependency between DeptId and DeptName can be
determined as DeptName is functionally dependent on DeptId −
DeptId -> DeptName

Excellence and Service


CHRIST
Deemed to be University

Key Terms Description


Axioms is a set of inference rules used to infer all the
Axiom
functional dependencies on a relational database.

It is a rule that suggests if you have a table that appears to


contain two entities which are determined by the same
Decomposition
primary key then you should consider breaking them up into
two different tables.
It is displayed on the right side of the functional dependency
Dependent
diagram.
It is displayed on the left side of the functional dependency
Determinant
Diagram.
It suggests that if two tables are separate, and the PK is the
Union
same, you should consider putting them. together

Excellence and Service


CHRIST
Deemed to be University

Armstrong’s Axioms Property of Functional Dependency


● Armstrong’s Axioms property was developed by William Armstrong
in 1974 to reason about functional dependencies.

● The property suggests rules that hold true if the following are
satisfied:

1. Transitivity
If A->B and B->C, then A->C i.e. a transitive relation.
2. Reflexivity
If B is a subset of A, then A-> B.
3. Augmentation
If A->B, then AC->BC

● [A, B and C are set of attributes]

Excellence and Service


CHRIST
Deemed to be University

Types of Functional Dependency

1. Trivial Functional Dependency


2. Non-Trivial Functional Dependency
3. Completely Non-Trivial Functional Dependency
4. Multivalued Dependency
5. Transitive Dependency

Excellence and Service


CHRIST
Deemed to be University

Trivial Functional Dependency

● The Trivial dependency is a set of attributes which are called a trivial


if the set of attributes are included in that attribute.
So, X -> Y is a trivial functional dependency if Y is a subset of X.

Example:
Consider this table of with two columns Emp_id and Emp_name.
{Emp_id, Emp_name} -> Emp_id is a trivial functional dependency as
Emp_id is a subset of {Emp_id,Emp_name}.

Emp_id Emp_name
AS555 Harry
AS811 George
AS999 Kevin

Excellence and Service


CHRIST
Deemed to be University

Non –Trivial Functional Dependency

● Nontrivial Functional dependency occurs when A->B holds true where B is not
a subset of A.
● In a relationship, if attribute B is not a subset of attribute A, then it is
considered as a non-trivial dependency.
● Example:

(Company} -> {CEO} (if we know the Company, we knows the CEO name)
But CEO is not a subset of Company, and hence it’s non-trivial functional
dependency.
Company CEO Age
Microsoft Satya Nadella 51
Google Sundar Pichai 46
Apple Tim Cook 57

Excellence and Service


CHRIST
Deemed to be University

Multivalued Dependency
● Multivalued dependency occurs in the situation where there are
multiple independent multivalued attributes in a single table.
● A multivalued dependency is a complete constraint between two
sets of attributes in a relation. It requires that certain tuples be
present in a relation.
- maf_year and color are independent of each other but dependent on
car_model.
- these two columns are said to be multivalue dependent on car_model.
● This dependence can be represented like this:
car_model -> maf_year
Car_model Maf_year Color
car_model-> colour H001 2017 Metallic
H001 2017 Green
H005 2018 Metallic
H005 2018 Blue
H010 2015 Metallic
H033 2012 Gray

Excellence and Service


CHRIST
Deemed to be University

Transitive Dependency
● A Transitive Dependency is a type of functional dependency which happens
when “t” is indirectly formed by two functional dependencies.
● Example:
{Company} -> {CEO} (if we know the compay, we know its CEO’s name)
{CEO } -> {Age} If we know the CEO, we know the Age

according to the rule of rule of transitive dependency:


{ Company} -> {Age} should hold, that makes sense because if we know the
company name, we can know his age.

Company CEO Age


Microsoft Satya Nadella 51
Google Sundar Pichai 46
Alibaba Jack Ma 54

Excellence and Service


CHRIST
Deemed to be University

Advantages of Functional Dependency

● Functional Dependency avoids data redundancy. Therefore


same data do not repeat at multiple locations in that
database
● It helps you to maintain the quality of data in the database
● It helps you to defined meanings and constraints of
databases
● It helps you to identify bad designs
● It helps you to find the facts regarding the database design

Excellence and Service


CHRIST
Deemed to be University
Lossless decomposition
● Lossless join decomposition is a decomposition of a relation R into relations R1,R2
such that if we perform natural join of two smaller relations it will return the original
relation.
● This is effective in removing redundancy from databases while preserving the
original data.
● Lossless decomposition becomes feasible to reconstruct the relation R from
decomposed tables R1 and R2 by using Joins.
● In Lossless Decomposition the criteria for selecting common element is that the
common element must be a candidate key or super key in either of relation R1,R2 or
both.
● Decomposition of a relation R into R1 and R2 is a lossless-join decomposition if at
least one of the following functional dependencies are in F+ (Closure of functional
dependencies)
R1 ∩ R2 → R1
OR
R1 ∩ R2 → R2

Excellence and Service


CHRIST
Deemed to be University

● Question 1:
Let R (A, B, C, D) be a relational schema with the following functional
dependencies:
A → B,
B → C,
C → D and
D→B
The decomposition of R into (A, B), (B, C), (B, D)

(A) gives a lossless join, and is dependency preserving


(B) gives a lossless join, but is not dependency preserving
(C) does not give a lossless join, but is dependency preserving
(D) does not give a lossless join and is not dependency preserving

Excellence and Service


CHRIST
Deemed to be University

Lossless-Join Decomposition

● Decomposition of R into R1 and R2 is a lossless-join decomposition if at least


one of the following functional dependencies are in F+ (Closure of functional
dependencies)

R1 ∩ R2 → R1 OR R1 ∩ R2 → R2

● Decomposition of R into R1 and R2 is a dependency preserving


decomposition if closure of functional dependencies after decomposition is
same as closure of FDs before decomposition.
A simple way is to just check whether we can derive all the original FDs from
the FDs present after decomposition.

Excellence and Service


CHRIST
Deemed to be University

Dependency Preservation

● Decomposition of R into R1 and R2 is a dependency


preserving decomposition if closure of functional
dependencies after decomposition is same as closure of FDs
before decomposition.

● A simple way is to just check whether we can derive all the


original FDs from the FDs present after decomposition.

Excellence and Service


CHRIST
Deemed to be University

Prime attributes and non prime attributes

● An attribute that is a part of any candidate key is


known as prime attribute

● An attribute that is not part of any candidate key is


known as non-prime attribute
teacher_id subject teacher_age
111 Maths 38
Candidate Keys: {teacher_id, subject}
111 Physics 38
222 Biology 38 Non prime attribute: teacher_age

333 Physics 40
333 Chemistry 40

Excellence and Service


CHRIST
Deemed to be University

Example Problems on Functional Dependency

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Normalization
● Database Design Techniques
1. ER Modeling (Top down Approach)
2. Normalization (Bottom Up approach)

● Problems Caused by Redundancy - Storing the same information


redundantly, that is, in more than one place within a database, can lead to
several problems:
○ Redundant storage: Some information is stored repeatedly.
○ Update anomalies: If one copy of such repeated data is updated, an
○ inconsistency is created unless all copies are similarly updated.
○ Insertion anomalies: It may not be possible to store some information unless
○ some other information is stored as well.
○ Deletion anomalies: It may not be possible to delete some information without losing
some other information as well.

Excellence and Service


CHRIST
Deemed to be University

Anamolies

Below table University consists of seven attributes: Sid,


Sname, Cid, Cname, Fid, Fname, and Salary. And the Sid
acts as a key attribute or a primary key in the relation.
Table: University

Sid Sname Cid Cname Fid Fname Salary


1 Ram C1 DBMS F1 Sachin 30000
2 Shyam C2 Java F2 Boby 28000
3 Ankit C1 DBMS F1 Sachin 30000
4 saurabh C1 DBMS F1 Sachin 30000

Excellence and Service


CHRIST
Deemed to be University

● Insertion Anomaly
● Suppose a new faculty joins the University, and the Database Administrator
inserts the faculty data into the above table. But he is not able to insert
because Sid is a primary key, and can’t be NULL. So this type of anomaly is
known as an insertion anomaly.
● Table: University

Excellence and Service


CHRIST
Deemed to be University

● Delete Anomaly
● When the Database Administrator wants to delete the student details
of Sid=2 from the above table, then it will delete the faculty and course
information too which cannot be recovered further.

Excellence and Service


Update Anomaly
When the Database Administrator wants to change the salary of faculty F1 from 30000 to 40000 in above table University, then the database will up
CHRIST
Deemed to be University

● Update Anomaly
● When the Database Administrator wants to change the salary of faculty F1
from 30000 to 40000 in above table University, then the database will update
salary in more than one row due to data redundancy. So, this is an update
anomaly in a table.

Excellence and Service


CHRIST
Deemed to be University

What is Normalization?

● Normalization is the process of minimizing redundancy from a relation or


set of relations. Redundancy in relation may cause insertion, deletion and
updation anomalies. So, it helps to minimize the redundancy in
relations. Normal forms are used to eliminate or reduce redundancy in
database tables.

Excellence and Service


CHRIST
Deemed to be University

Types of Normal Forms

● 1 NF
● 2 NF
● 3 NF
● BCNF – Boyec Codd Normal Form
● 4 NF
● 5 NF
● DKNF – Domain Key Normal Form

● Standard Normal Form – 3 NF

Excellence and Service


CHRIST
Deemed to be University

First Normal Form

● If a relation does not contain any composite or multi-valued attribute then it is


said to be in 1 NF.
● A relation is in first normal form if every attribute in that relation is singled
valued attribute (or atomic value).

A composite key is a primary


key composed of multiple
columns used to identify a
record uniquely

Excellence and Service


CHRIST
Deemed to be University

● Example 1 – Relation STUDENT in table 1 is not in 1NF because of


multi-valued attribute STUD_PHONE. Its decomposition into 1NF has
been shown in table 2.

Excellence and Service


CHRIST
Deemed to be University

Example 2: 1 NF

Excellence and Service


CHRIST
Deemed to be University

Second Normal Form

● A relation is in 2NF if it is in 1NF and has No Partial Dependency

● Partial Dependency – no non-prime attribute is dependent on any proper


subset of any candidate key of the table.

● i.e., all non-prime attributes are fully functional dependent on the primary key

Excellence and Service


CHRIST
Deemed to be University

Example

candidate key {STUD_NO, COURSE_NO}

FD: COURSE_NO -> COURSE_FEE

COURSE_FEE is dependent on COURSE_NO, which is


a proper subset of the candidate key which is a partial
dependency and so this relation is not in 2NF.

To convert the above relation to 2NF, we


need to split the table into two tables such as :

Table 1: STUD_NO, COURSE_NO


Table 2: COURSE_NO, COURSE_FEE

Excellence and Service


CHRIST
Deemed to be University

● Example 2 – Consider following functional dependencies in relation R (A, B


, C, D )
● AB -> C [A and B together determine C]
● BC -> D [B and C together determine D]
● In the above relation, AB is the only candidate key and there is no partial
dependency, i.e., any proper subset of AB doesn’t determine any non-prime
attribute.

Excellence and Service


CHRIST
Deemed to be University

Third Normal Form

● A relation will be in 3NF if it is in 2NF and no transitive dependency exists for


non-prime attributes.
● A relation is in 3NF if at least one of the following condition holds in every
non-trivial function dependency X –> Y
○ X is a super key.
○ Y is a prime attribute (each element of Y is part of some candidate key).
● Transitive dependency – If A->B and B->C are two FDs then A->C is called
transitive dependency.

Excellence and Service


CHRIST
Deemed to be University

Example

FD set: {STUD_NO -> STUD_NAME,


STUD_NO -> STUD_STATE,
STUD_STATE -> STUD_COUNTRY,
STUD_NO -> STUD_AGE}

● Candidate Key: {STUD_NO}

● For this relation, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true.
● So STUD_COUNTRY is transitively dependent on STUD_NO.
● It violates the third normal form.
● To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO,
STUD_NAME, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:

● Table 1: STUDENT (STUD_NO, STUD_NAME, STUD_STATE, STUD_AGE)

● Table 2: STATE_COUNTRY (STATE, COUNTRY)

Excellence and Service


CHRIST
Deemed to be University

BCNF – Boyce Codd NF

● BCNF is the advance version of 3NF. It is stricter than 3NF.


● A table is in BCNF if every functional dependency X → Y, X is the super key of the table.
● For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

● Key Points
○ BCNF is free from redundancy.
○ If a relation is in BCNF, then 3NF is also also satisfied.
○ If all attributes of relation are prime attribute, then the relation is always in 3NF.
○ A relation in a Relational Database is always and at least in 1NF form.
○ Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.
○ If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the
Relation is always in 2NF( because no Partial functional dependency possible).
○ Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost
FD(s) is not required, else normalize till 3NF only.
○ There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems
it’s generally not required to go beyond BCNF.

Excellence and Service


CHRIST
Deemed to be University

Example Problem:

EMP_ID EMP_COUN EMP_DEPT DEPT_TYPE EMP_DEPT_


TRY NO

264 India Designing D394 283


264 India Testing D394 300
364 UK Stores D283 232
364 UK Developing D283 549

● In the above table Functional dependencies are as follows:

● EMP_ID → EMP_COUNTRY
● EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Excellence and Service


CHRIST
Deemed to be University

● Candidate key: {EMP-ID, EMP-DEPT}


● The table is not in BCNF because neither EMP_DEPT nor EMP_ID
alone are keys.
● To convert the given table into BCNF, we decompose it into three
tables: EMP_DEPT_MAPPING table:

EMP_COUNTRY table: EMP_ID EMP_DEPT

EMP_ID EMP_COUNTRY 264 Designing


264 Testing
264 India
364 Stores
364 UK
364 Developing
EMP_DEPT table
Functional dependencies:
EMP_DEPT DEPT_TYPE EMP_DEPT_NO EMP_ID → EMP_COUNTRY
EMP_DEPT → {DEPT_TYPE, EMP_DE
Designing D394 283
PT_NO}
Testing D394 300 Candidate keys:
For the first table: EMP_ID
Stores D283 232 For the second table: EMP_DEPT
Developing D283 549 For the third table: {EMP_ID,
Excellence and Service EMP_DEPT}
CHRIST
Deemed to be University

Fourth Normal Form

● A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-
valued dependency.

● Multi-valued Dependency: For a dependency A → B, if for a single value of


A, multiple values of B exists, then the relation will be a multi-valued
dependency.

Excellence and Service


CHRIST
Deemed to be University

● Student Table
student_id Name Course
101 Ankit Python
102 Kartikey Java
103 Krishna R programming
101 Ankit JAVA
105 Akash PHP

● In the above relation, Name and Course are two independent attributes and
both are dependent on student_id.
In this case, these two attributes can be called as multivalued dependent on
student_id.
● Following are the representation of these dependencies:
Student_id  Name
Student_id  Course
● So, to make the above relation into the fourth normal form (4NF), decompose
it into two tables:

Excellence and Service


CHRIST
Deemed to be University

Student_name
student_id Name
101 Ankit
102 Kartikey
103 Krishna
105 Akash

Student_course

student_id Course
101 Python
102 Java
103 R programming
101 JAVA
105 PHP

Excellence and Service


CHRIST
Deemed to be University

Fifth Normal Form

● A relation is in 5NF if it is in 4NF and not contains any join dependency and
joining should be lossless.

● 5NF is satisfied when all the tables are broken into as many tables as
possible in order to avoid redundancy.
● 5NF is also known as Project-join normal form (PJ/NF).

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

DKNF – Domain Key normal form

● No anamolies

● Domain – columns

● No duplicate values, not null

Excellence and Service


CHRIST
Deemed to be University

Problem 1:
R(v,w,x,y,z)
x->yv
y->z
z->y
vw->x
Find the relation is in which Normal
form?

Excellence and Service


CHRIST
Deemed to be University

Problem 2:
R(A,B,C,D,E)
AB->D
D->A
BC->DE
Find the relation is in which Normal form?

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


Problem 3:
R(A,B,C) CHRIST
A->B Deemed to be University
B->C
C->A
Find the relation is in which Normal form?

Problem 4:
R(A,B,C,D,E)
BC->ADE
D->B

Problem 5:
R(A,B,C,D,E)
CE->D
D->B
C->A

Problem 6:
R(A,B,C,D,E,F,G,H)
AB->C
A->DE
B->F
F->GH

Excellence and Service


CHRIST
Deemed to be University

PROCEDURES AND FUNCTIONS


● A procedure is a named PL/SQL block which performs one or more specific task.
This is similar to a procedure in other programming languages. A procedure has a
header and a body.
● The header consists of the name of the procedure and the parameters or variables
passed to the procedure.
● The body consists or declaration section, execution section and exception section
similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL
Block but it is named for repeated usage.
● We can pass parameters to procedures in three ways :
Parameters Description

IN type These types of parameters are used to send values to stored procedures.

OUT type These types of parameters are used to get values from stored procedures. This is similar to a
return type in functions.

IN OUT type These types of parameters are used to send values and get values from stored procedures.

● A procedure may or may not return any value.

Excellence and Service


CHRIST
Deemed to be University

PROCEDURES AND FUNCTIONS


Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name


(<Argument> {IN, OUT, IN OUT} Datatype) {IS, AS} // beginning of the body of the procedure
Variable Declaration
BEGIN
PL/SQL Sub program body
EXCEPTION The syntax within the brackets [ ] indicate they are
Exception section optional. By using CREATE OR REPLACE together
END procedure_name; the procedure is created if no other procedure with
/ the same name exists or the existing procedure is
replaced with the current code.

Example:

create or replace procedure p2(id in number,sal in number)


is begin
insert into empl values(id,sal);
end p2;
/

Excellence and Service


CHRIST
Deemed to be University

● exec p2(101,5000); // to insert new record using procedure

● Advantages of Procedures:
● Security
● Performance
● Memory allocation
● Productivity

Excellence and Service


CHRIST
Deemed to be University

IN Mode

● This parameter helps to pass values to the subprogram being called.


● It acts like a constant and cannot be assigned a value.

● You can refer the PROCEDURES syntax in this link:

● https://docs.oracle.com/database/121/LNPLS/controlstatements.htm#LNPLS3
88

Excellence and Service


CHRIST
declare Deemed to be University
x scheme%rowtype;
R number;
sch varchar2(20);
cursor c1 is select * from scheme;
begin
for x in c1 loop
dbms_output.put_line('=============================================');
dbms_output.put_line('. SCHEME TABLE ');
dbms_output.put_line('=============================================');
dbms_output.put_line('ACNO '||x.acno||' '||'Name '||x.name);
dbms_output.put_line('===============================================');
dbms_output.put_line('SCHEME P N R SI FA ');
dbms_output.put_line('===============================================');
sch:='I Scheme';
R:=10;
pnr6(sch,x.P,x.N,R);
sch:='II Scheme';
R:=12;
pnr6(sch,x.P,x.N,R);
sch:='III Scheme';
R:=15;
pnr6(sch,x.P,x.N,R);
dbms_output.put_line('===============================================');
end loop;
commit;
end;
/
Excellence and Service
CHRIST
Deemed to be University

● 2. Create a table with the following fields: SNO, NAME,


SUBJECT,MARKS. Insert 5 records
Write a procedure to compute REMARKS
Display the table as a report using cursor.

Excellence and Service


CHRIST
Deemed to be University

Procedure Code:
SQL> create or replace procedure marks_proc(sub in varchar2,m in number, tot in out number) is
2 rem varchar2(10);
3 begin
4 if m >= 75 then rem := 'DISTINCT';
5 elsif m >= 60 then rem := 'I Class';
6 elsif m >= 50 then rem := 'II class';
7 elsif m >= 35 then rem := 'III class';
8 else
9 rem := 'Fail';
10 end if;
11 tot := tot + m;
12 dbms_output.put_line(sub||' '||to_char(m)||' '||rem);
13 end;
14 /

Procedure created.

Excellence and Service


CHRIST
Deemed to be University

Cursor Program:
declare
x dian_studd%rowtype;
tot number;
cursor c1 is select * from dian_studd;
begin
for x in c1 loop
dbms_output.put_line(' subjectwise remarks ');
dbms_output.put_line('=====================================================');
dbms_output.put_line('sno'||' '||to_char(x.sno)||' '||'name'||' '||x.name);
dbms_output.put_line('======================================================');
dbms_output.put_line('Subject Marks Remarks');
dbms_output.put_line('=====================================================');
tot := 0;

marks_proc('BASIC',x.BM,tot);
marks_proc('COBOL',x.CM,tot);
marks_proc('FORTRAN',x.FM,tot);

dbms_output.put_line('======================================================');
dbms_output.put_line('Total'||' '||to_char(tot));
dbms_output.put_line('======================================================');
end loop;
end;
Excellence and Service
CHRIST
Deemed to be University

Functions

● "A procedures or function is a group or set of SQL and PL/SQL statements


that perform a specific task.“
● A function and procedure is a named PL/SQL Block which is similar .
● The major difference between a procedure and a function is, a function must
always return a value, but a procedure may or may not return a value.

Excellence and Service


CHRIST
Deemed to be University

Syntax:

FUNCTION name [(parameter[, parameter,….])] RETURN datatype IS


[local declarations]
BEGIN
executable statements
EXCEPTION
exception handlers
END[name];

● Like a procedure functions has 2 parts: the specification and the body
● One or more RETURN statements must appear in the executable part of a
function.

Excellence and Service


CHRIST
Deemed to be University

Question: Functions

Create a table named “YOURNAMESALARY” with the following


fields: ENO number(5) primary key,
Name varchar2(10),
BS numeric(5),
Deptno number(2)

Insert 10 records.
Create a function dianasal_ok to display the minimum salary and
maximum salary. Determine if an employee salary is out of range.
Call the function using Cursor and display the output.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Triggers in Oracle
● 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 −
○ A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
○ A database definition (DDL) statement (CREATE, ALTER, or DROP).
○ A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
● Triggers can be defined on the table, view, schema, or database with which the event is
associated.
● Benefits 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

Excellence and Service


CHRIST
Deemed to be University

CREATE [OR REPLACE] TRIGGER trigger_name − Creates or


CREATE [OR REPLACE ] TRIGGER trigger_name replaces an existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF }
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger
{INSERT [OR] | UPDATE [OR] | DELETE} will be executed. The INSTEAD OF clause is used for creating trigger
[OF col_name] on a view.
ON table_name
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
[REFERENCING OLD AS o NEW AS n]
operation.
[FOR EACH ROW]
WHEN (condition) [OF col_name] − This specifies the column name that will be updated.
DECLARE
[ON table_name] − This specifies the name of the table associated
Declaration-statements with the trigger.
BEGIN
Executable-statements [REFERENCING OLD AS o NEW AS n] − This allows you to refer new
EXCEPTION and old values for various DML statements, such as INSERT,
UPDATE, and DELETE.
Exception-handling-statements
END; [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger
will be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called
a table level trigger.

WHEN (condition) − This provides a condition for rows for which the
trigger would fire. This clause is valid only for row-level triggers.

Excellence and Service


CHRIST
Deemed to be University

Example

SQL> create or replace trigger displaysalchanges


before delete or insert or update on custom The following points need to be considered here −
for each row OLD and NEW references are not available for table-
when (new.id > 0) level triggers, rather you can use them for record-
declare level triggers.
saldiff number;
begin If you want to query the table in the same trigger,
saldiff := :new.salary - :old.salary; then you should use the AFTER keyword, because
dbms_output.put_line('Old salary:' || :old.salary); triggers can query the table or change it again only
dbms_output.put_line('new salary:' || :new.salary); after the initial changes are applied and the table is
dbms_output.put_line('salary difference:' || saldiff); back in a consistent state.
end;
/ The above trigger has been written in such a way
that it will fire before any DELETE or INSERT or
Trigger created. UPDATE operation on the table, but you can write
your trigger on a single or multiple operations, for
example BEFORE DELETE, which will fire whenever
a record will be deleted using the DELETE operation
https://www.tutorialspoint.com/plsql/plsql_triggers.htm on the table.

Excellence and Service


CHRIST
Deemed to be University

Output:

insert into custom values(64,'a',35,'www',4000);


Old salary:
new salary:4000
salary difference:

update custom set salary = 2000 where id = 1;


Old salary:4000
new salary:2000
salary difference:-2000

1 row updated.

Excellence and Service


CHRIST
Deemed to be University

Excellence and Service


CHRIST
Deemed to be University

Thank you

Excellence and Service

You might also like