Unit 2
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).
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.
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
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
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.
● 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
CREATE TABLE
Example:
● CREATE TABLE Students (ROLLNO int(3), NAME varchar(20), SUBJECT
varchar(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;
DROP TABLE
● DROP - It is used to This command deletes both the structure and record
stored in the table.
● Example:
DROP TABLE EMPLOYEE;
RENAME TABLE
TRUNCATE TABLE
● TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
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.
● 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
Column Constraint:
TABLE CONSTRAINT:
● To define one primary key on one column
● create table department(DeptId number, Deptname varchar2(20), ClassId number,
primary key(DeptId));
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.
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.
● create table book(id number primary key, name varchar2(10), cc number(1), cost
number(10) check(cost > 100));
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);
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
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
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
Examples
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.
Example
● Example: To delete all tuples from the loan relation
● Example: Delete all loans with loan amounts between $1300 and $1500.
Example
● Example: delete the records of all accounts with balances below the average
at the bank
UPDATE
Syntax:
UPDATE tablename
SET [column_name1= value1,...columnnameN = valueN]
[WHERE CONDITION]
Example
Example
MERGE
DQL Commands
● The keyword all to specify explicitly that duplicates are not removed:
● 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
● 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
Operators, Functions,
Expressions and
Conditions
Operators
● Arithmetic operators
● Character operators
● Comparison operators
● Logical operators
● Set operators
Arithmetic operators
Character Operators
select customer_city || customer_street from customer; // concatenation
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;
Logical Operators
Set Operations
● 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
Functions
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;
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;
Date Functions
Date Formats
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
Conditional Expressions
● CASE
○ IF-THEN-ELSE statement
● DECODE
○ IF-THEN-ELSE statement
Conversion Functions
To_CHAR
● TO_CHAR(number, 'format_model')
● Example: select to_char(sysdate,'dd-mm-yyyy')
from dual;
● Default: dd-mon-yy
Nested Functions
SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8),'_US'))
FROM employees
WHERE department_id = 60;
● Example: Select those branches where the average account balance is more than $1200.
count
● Example: find the maximum across all branches of the total balance at each
branch
sum
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.
● Group by
● Order by
● Where
● Having
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;
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.
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.
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.
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.
● 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.
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.
INNER JOIN
Syntax
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
● 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;
● 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;
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;
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;
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 ]
SUBQUERIES
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
● Example: find all customers who do have a loan at the bank, but do not have
an account at the bank
● Example: selects the names of customers who have a loan at the bank, and
whose names are neither Smith nor Jones
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 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
● 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).”
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
● 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
● 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.
● The as clause can appear in both the select and from clauses.
● 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
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.
● 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
SYNONYM
● Syntax:
● Create [public] synonym <synonym name> for <table name>
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.
● 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
Clusters
● 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
● Syntax:
● Create cluster <cluster name> (column_name datatype)
SEQUENCE
MAXVALUE maximum value cycle: When sequence reaches its set_limit it starts from beginning.
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
Derived Relations
● Example: find the maximum across all branches of the total balance at each
branch
● 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;
● 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.
SQL Functions
● Character function
● Number Function
● Date Function
● Conversion function
● General function
DCL Commands
● Grant - The grant statement is used to confer authorization.
● 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:
Creating users
● conn jon;
● Enter password:
● ERROR:
● ORA-01045: user JON lacks CREATE SESSION privilege; logon denied
● Example: the system returns an error if there are any cascading revokes, and
does not carry out the revoke action.
TCL Commands
● COMMIT Statement -- commit (make persistent) all changes for the current
transaction
● ROLLBACK Statement -- roll back (rescind) all changes for the current
transaction
Example
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
Declare
<Declaration Section>
Begin
<Executable Commands>
Exception
<Exception Handling>
End;
Declaration Section
● 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;
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
● 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
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;
Example: Method 2
declare
ns constant number(2) := 2;
mtotal number;
maverage number(6,2);
mrem varchar2(5);
begin
for x in c1 loop
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;
● 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.
● 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
● 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
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
● 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
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
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
● 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)
Lossless-Join Decomposition
R1 ∩ R2 → R1 OR R1 ∩ R2 → R2
Dependency Preservation
333 Physics 40
333 Chemistry 40
Normalization
● Database Design Techniques
1. ER Modeling (Top down Approach)
2. Normalization (Bottom Up approach)
Anamolies
● 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
● 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.
● 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.
●
What is Normalization?
● 1 NF
● 2 NF
● 3 NF
● BCNF – Boyec Codd Normal Form
● 4 NF
● 5 NF
● DKNF – Domain Key Normal Form
Example 2: 1 NF
● i.e., all non-prime attributes are fully functional dependent on the primary key
Example
Example
● 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:
● 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.
Example Problem:
● EMP_ID → EMP_COUNTRY
● EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
● A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-
valued dependency.
● 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:
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
● 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).
● No anamolies
● Domain – columns
Problem 1:
R(v,w,x,y,z)
x->yv
y->z
z->y
vw->x
Find the relation is in which Normal
form?
Problem 2:
R(A,B,C,D,E)
AB->D
D->A
BC->DE
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
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.
Example:
● Advantages of Procedures:
● Security
● Performance
● Memory allocation
● Productivity
IN Mode
● https://docs.oracle.com/database/121/LNPLS/controlstatements.htm#LNPLS3
88
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.
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
Syntax:
● 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.
Question: Functions
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.
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
WHEN (condition) − This provides a condition for rows for which the
trigger would fire. This clause is valid only for row-level triggers.
Example
Output:
1 row updated.
Thank you