0% found this document useful (0 votes)
64 views54 pages

Unit-2 Notes

The document discusses SQL and query processing. It covers SQL concepts like data definition, data manipulation, database structures, and query processing. Key topics include SQL clauses like SELECT, FROM, and WHERE; data types; creating, modifying and deleting database objects; and query optimization techniques.

Uploaded by

Shyam
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)
64 views54 pages

Unit-2 Notes

The document discusses SQL and query processing. It covers SQL concepts like data definition, data manipulation, database structures, and query processing. Key topics include SQL clauses like SELECT, FROM, and WHERE; data types; creating, modifying and deleting database objects; and query optimization techniques.

Uploaded by

Shyam
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/ 54

UNIT-II SQL AND QUERY PROCESSING

SQL: Data Definition – Domain types – Structure of SQL Queries -


Modifications of the database – Set Operations – Aggregate Functions –
Null Values – Nested Sub queries – Complex Queries – Views – Joined
relations – Complex Queries – PL/SQL: Functions, Procedures, Triggers,
Cursors -Embedded SQL – Query Processing – Heuristics for Query
Optimization.

STRUCTURED QUERY LANGUAGE (SQL):

SQL stands for Structured Query Language.SQL lets you access and manipulate
databases . In 1986, the American National Standards Institute (ANSI) and the International
organization for standardization (ISO) published an SQL Standard, called SQL-86. IBM
published its own corporate SQL standard, the systems Application Architecture Database
interface (SAA-SQL) in 1987. ANSI Published on extended standard for SQL, SQL-89, in
1989. The next version of the standard was SQL-92, and the most recent version is
SQL:1999.

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

The SQL language has several parts:


 Data-Definition language (DDL): The SQL DDL provides commands for defining
relation schemas, deleting relations, and modifying relation schemas.
 Interactive data – manipulation language (DML): The SQL DML includes a query
language based on both the relational algebra and the tuple relational calculus. It
includes also commands to insert tuples into, delete tuples from, and modify
tuples in the database.

 View definition: The SQL DDL includes commands for defining views.
 Transaction control: SQL includes commands for specifying the beginning and
ending of transactions.
 Embedded SQL and dynamic SQL: Embedded and SQL dynamic SQL define
how SQL statements can be embedded within general– purpose programming
languages, such as C, C++, Java, PL/I, Cobol, Pascal, and FORTRAN.
 Integrity: The SQL DDL includes commands for specifying integrity constraints
that the data stored in the databases must satisfy. Updates that violated integrity
constraints are disallowed.

 Authorization: The SQL DDL includes commands for specifying access rights to
relations and views.

Data Definition:
DDL is short name of Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.
1)CREATE - to create a database and its objects like (table, index, views, store procedure,
function, and triggers)
Syntax
CREATE TABLE table_name (column1datatype,column2datatype,column3datatype,....);
The column parameters specify the names of the columns of the table.The datatype
parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Example
CREATE TABLE Persons(PersonIDint,LastNamevarchar(255),FirstNamevarchar(255),
Addressvarchar(255),Cityvarchar(255));

2)ALTER - alters the structure of the existing database


SYNTAX
ALTER TABLE table_name ADD column_name datatype;
Example
ALTER TABLE Customers ADD Email varchar(255);
3)DROP - delete objects from the database

Syntax:
DROP TABLE table_name;

Example:

DROP TABLE Shippers;

4)TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
Difference between Drop and Truncate command

DROP TRUNCATE

The DROP command in SQL The TRUNCATE command is used to


removes an entire table from a remove all of the rows from a table,
database including its definition, regardless of whether or not any
indexes, constraints, data etc. conditions are met and resets the table
definition.

It is a DDL(Data Definition It is also a DDL(Data Definition


Language) command. Language) command.

The table space is completely freed The table still exists in the memory.
from the memory.

All the integrity constraints are The integrity constraints still exist in the
removed. table.

Requires ALTER and CONTROL Only requires the ALTER permissions to


permissions on the table schema truncate the table.
and table respectively, to be able to
perform this command.

DROP command is much slower It is faster than both DROP and DELETE
than TRUNCATE but faster than commands.
DELETE.
Syntax for Truncate and Drop command are same
TRUNCATE TABLE Table name;

5)COMMENT - add comments to the data dictionary


Single line comments start with --.
Any text between -- and the end of the line will be ignored (will not be executed).
The following example uses a single-line comment as an explanation:
--Select all:
SELECT * FROM Customers;

The following example uses a single-line comment to ignore the end of a line:

SELECT * FROM Customers -- WHERE City='Berlin';


The following example uses a single-line comment to ignore a statement:
--SELECT * FROM Customers;
SELECT * FROM Products;
6)RENAME - rename an object
The RENAME TABLE statement is used to change the table name.
Syntax:
We can also use the ALTER TABLE statement to change the table name.
Syntax:
ALTER tableName RENAME TO newTableName;
Example:
RENAME EMPLOYEE1 TO EMPLOYEE2;
Or
ALTER EMPLOYEE1 RENAME TO EMPLOYEE2;

Domain types:
Domain Types in SQL: The SQL standard supports a variety of built-in domain types,
including:
 char (n): A fixed-length character string with user-specified length n.

 varchar (n): A variable-length character string with user-specified maximum


length n.

 int: An integer (a finite subset of the integers that is machine dependent).


 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.
 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.

 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. It is also possible to
store time zone information along with the time.

 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).
Date and time values can be specified like this:
date „2008-02-25‟
time ‟09:30:00‟
timestamp „2008-02-25 10:29:01.45‟
An expression of the form cast e as t to convert a character string (or string valued
expression) e to the type t, where t is one of date, time, or timestamp. To extract individual
fields of a date or time value d, extract (field from d) can be used, where field can be one of
year, month, day, hour, minute, or second.
SQL allows comparison operations of all the domains, and it allows both arithmetic and
comparison operations on the various numeric domains. SQL also provides a data type called
interval, and it allows computations based on dates and times and on intervals.
SQL allows the domain declaration of an attribute to include the specification not null and
thus prohibits the insertion of a null value for this attribute.

Structure of SQL Queries:


A relational database consists of a collection of relations, each of which is assigned a unique
name. The basic structure of an SQL expression consists of three clauses: select, from, and
where. A typical SQL query has the form
select A1 , A2 , …, An from r1, r 2, …, r m where P
Each Ai presents an attribute, and each r i a relation. P is a predicate.

 The select Clause: The result of an SQL query is a relation. Consider a simple
query
select branch–name from loan
The result is a relation consisting of a single attribute with the heading branch–name. SQL
allows duplicates in relations as well as in the results of SQL expressions.
To force the elimination of duplicates, insert the keyword distinct after select. To display only
distinct branch–names, the above query can be rewritten as
select distinct branch–name from loan
The keyword all is used to specify explicitly that duplicates are not removed.
select all branch–name from loan
A select clause of the form select * indicates that all attributes of all relations appearing in the
from clause are selected.
The select clause may also contain arithmetic expressions involving the operators +, –, *, and
/ operating on constants or attributes of tuples.
SQL also provides special data types, and allows several arithmetic functions to operate on
these types.
 The where Clause: Consider the query “Find all loan numbers for loans made at
the Perry ridge branch with loan amounts greater than $1200”. This query can be
written in SQL as
select loan–number from loan where branch name = “Perry ridge” and amount > 1200
SQL uses the logical connections and, or, and not – rather than the mathematical symbols
,, and  – in the where clause. The operands of the logical connectives can be expressions
involving the comparison operators, <, <=, >, >=, =, and <>.
SQL includes a between comparison operator to simplify where clauses that specify that a
value be less than or equal to some value and greater than or equal to some other value. The
query to find the loan number of those loans with loan amounts between $90,000 and
$100,000 is
select loan–number from loan where amount between 90000 and 100000
instead of
select loan–number from loan where amount <= 100000 and amount >= 90000
Similarly, the not between comparison operator can also be used.
 The from Clause: The from clause by itself defines a Cartesian product of the
relations in the clause. Consider the query “Find the customer names, loan
numbers and loan amounts for all loans at the Perry ridge branch”. Assume that
customer–name, loan–number attributes are in borrower relation and loan–
number, branch–name, amount attributes are in loan relation. In SQL, this query
can be written as
select customer–name, borrower.loan–number, amount from borrower, loan
where borrower.loan–number = loan.loan–number and branch–name = “Perry ridge”.
SQL uses the notation relation–name.attribute–name to avoid ambiguity in cases where an
attribute appears in the schema of more than one relation.
 The Rename Operation: It is known that the names of the attributes in the result
are derived from the names of the attributes in the relations in the from clause.
However SQL provides a way for renaming the attributes of a result relation. It
uses the as clause, taking the form:
old–name as new–name
The following query replaces the attribute name loan–number with the name loan–id while
finding the customer names, loan numbers and loan amount those who have a loan from a
bank.
select customer–name, borrower.loan–number as loan–id, amount
from borrower, loan where borrower.loan–number = loan.loan–number
 Tuple Variables: A tuple variable in SQL must be associated with a particular
relation. Tuple variables are defined in the from clause by way of the as clause.
The query “For all customers who have a loan from the bank, find their names,
loan numbers, and loan amount”, can be rewritten as
select customer–name, T.loan–number, S.amount from borrower as T,
loan as S where T.loan–number = S.loan–number
A tuple variable is defined in the from clause by placing it after the name of the relation with
which it is associated, with the keyword as in between (the keyword as is optional).
Tuple variables are most useful for comparing two tuples in the same relation. The following
example finds the names of all branches that have assets greater than at least one branch
located in Brooklyn.
select distinct T.branch–name from branch as T, branch as S
where T.assets > S.assets and S.branch-city = „Brooklyn‟
 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 by using two special characters:
 Percent (%): The % character matches any substring.
 Underscore (_): The _ character matches any character.
Patterns are case sensitive; i.e., uppercase characters do not match lowercase characters, or
vice versa. To illustrate pattern matching, consider the following 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.


SQL expresses patterns by using the like comparison operator. Consider the query “Find the
names of all customers whose street address includes the substring „Main‟”. This query can
be written as
select customer-name from customer
where customer-street like „%Main%‟
For patterns to include the special pattern characters (% and _), SQL allows the specification
of an escape character. The escape character is used immediately before a special pattern
character to indicate that the special character is to be treated like a normal character. To
illustrate, consider the following patterns, which use a backslash (\) as the escape character:
 like „ab\%cd%‟ escape „\‟ matches all strings beginning with “ab%cd”.
 like „ab\\cd%‟ escape „\‟ matches all strings beginning with “ab\cd”.
SQL allows us to search for mismatches instead of matches by using the not like comparison
operator. SQL also permits a variety of functions on character strings, such as concatenation
(using “||”), extracting substrings, finding the length of strings, converting between uppercase
and lowercase, and so on. SQL:1999 also offers a similar to operation, which provides more
powerful pattern matching than the like operation.
 Ordering the Display of Tuples: The order by clause causes the tuples in the result
of a query to appear in sorted order. By default, the order by clause lists items in
ascending order. To specify the sort order, use desc for descending order or asc for
ascending order. Ordering can also be performed on multiple attributes.
Suppose to list the entire loan relation in descending order of amount, and if several loans
have the same amount, then to order them in ascending order by loan number, the query can
be written as
select * from loan order by amount desc, loan-number asc
Since sorting a large number of tuples may be costly, it should be done only when necessary.
 Duplicates: SQL formally defines not only what tuples are in the result of a query,
but also how many copies of each of those tuples appear in the result. The
duplicate semantics of an SQL query can be defined using multiset versions of the
relational operators.

Modifications of the database:


Referential integrity is a condition, which ensures that a value that appears in one relation for
a given set of attributes also appears for a certain set of attributes in another relation.
Let r1 (R1) and r2 (R2) be relations with primary keys K1 and K2 , respectively. A subset  of
R2 is a foreign key referencing K1 in relation r1 if it is required that, for every tuple t2 in r2 ,
there must be a tuple t1 in r1 such that t1 [K1] = t2 []. Requirements of this form are called
referential integrity constraints or subset dependencies, because the referential integrity
constraint can be written as  (r2)  K1 (r1). The symbol  is used to indicate the
projection operation.
Database modifications can cause violations of referential integrity. The following list of tests
must be made for each type of database modification to preserve the following integrity
constraint:

 (r2)  K (r1)
 Insert. If a tuple t2 is inserted into r2, the system must ensure that there is a tuple t 1
in r1 such that t1 [K] = t2 []. i.e. t2 []   K (r1).
 Delete. If a tuple t1 is deleted from r1, the system must compute the set of tuples in
r2 that reference t1 :   = t1 [K] (r2). If this set is not empty, either the delete
command is rejected as an error, or the tuples that reference t1 must
themselves be deleted.

 Update. Consider two cases for update: updates to the referencing relation (r 2),
and updates to the referenced relation (r1).
 If a tuple t2 is updated in relation r2, and the update modifies values for the foreign
key , then the system must ensure that t2 []  K (r1), where t2 denotes the
new value of tuple t2.
 If a tuple t1 is updated in r1, and the update modifies values for the primary key
(K), then the system must compute   = t1 [K] (r2) using the old value of t1 (the
value before the update is applied). If this set is not empty, the update is rejected
as an error, or the update is cascaded in a manner similar to delete.
Foreign keys can be specified as part of the SQL create table statement by using the foreign
key clause. By default, a foreign key references the primary key attributes of the referenced
table. SQL also supports a version of the references clause where a list of attributes of the
referenced relation can be specified explicitly. The specified list of attributes must be
declared as a candidate key of the referenced relation.
Consider the definition of an integrity constraint on the relation account with the referenced
relation branch:
create table branch (branch-name char (15), branch-city char (30), assets integer, primary key
(branch-name), check (assets >= 0))
create table account (account-number char (10), branch-name char (15), balance integer,
primary key (account-number), foreign key (branch-name) references branch on delete
cascade on update cascade, check (balance >= 0))
When a referential integrity constraint is violated, the normal procedure is to reject the action
that caused the violation.
Because of the clause on delete cascade associated with the foreign key declaration, if a
delete of a tuple in branch results in this referential integrity constraint being violated, the
system does not reject the delete. Instead, the delete “cascades” to the account relation,
deleting the tuple that referes to the branch that was deleted.
Similarly, the system does not reject an update to a field referenced by the constraint if it
violates the constraint; instead, the system updates the field branch-name in the referencing
tuples in account to the new value.
SQL also allows the foreign key clause to specify actions other than cascade, if the constraint
is violated. The referencing field branch-name can be set to null (by using set null in place of
cascade), or to the default value for the domain (by using set default).
If there is a chain of foreign key dependencies across multiple relations, a deletion or update
at one end of the chain can propagate across the entire chain.
When the foreign key constraint on a relation references the same relation, then if a cascading
update or delete causes a constraint violation that cannot be handled by a further cascading
operation, the system aborts the transaction, and all the changes caused by the transaction and
its cascading actions are undone.

Set Operations:
The SQL operations union, intersect, and except operate on relations and correspond to the
relational algebra operations , , and . The relations participating in the operations must
have the same set of attributes.
1)The Union Operation: The union operation automatically eliminates duplicates. The
following query finds all customers having a loan, an account, or both at the bank. If a
customer has several accounts or loans (or both) at the bank, then that customer will appear
only once in the result.
(select customer-name from depositor) union (select customer-name from borrower)
If all duplicates are to be retained, then write union all in place of union.
(select customer-name from depositor) union all (select customer-name from borrower)
The number of duplicate tuples in the result is equal to the total number of duplicates that
appear in both depositor and borrower. Thus, if a customer has three accounts and two loans
at the bank, then there will be five tuples with the same customer name in the result.
Syntax

SELECT column_name FROM table1


UNION
SELECT column_name FROM table2;
Example:
The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:


SELECT * FROM First
UNION
SELECT * FROM Second;
The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David
2)Union All:
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
Example: Using the above First and Second table.
Union All query will be like:
SELECT * FROM First
UNION ALL
SELECT * FROM Second;
The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3)Intersect:
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
Example:
Using the above First and Second table.
Intersect query will be:
SELECT * FROM First
INTERSECT
SELECT * FROM Second;
The resultset table will look like:

ID NAME

3 Jackson

4) EXCEPT OR MINUS:
o It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
Example
Using the above First and Second table.
Minus query will be:
SELECT * FROM First
MINUS
SELECT * FROM Second;
The resultset table will look like:

ID NAME

1 Jack

2 Harry
Aggregate Functions:
In database management an aggregate function is a function where the values of multiple
rows are grouped together as input on certain criteria to form a single value of more
significant meaning.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Now let us understand each Aggregate function with a example:
Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null
Count():
Count(*): Returns total number of records .i.e 6.
Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column salary
.i.e 4
Sum():
sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.
Avg():
Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
Min():
Min(salary): Minimum value in the salary column except NULL i.e., 40.
Max(salary): Maximum value in the salary i.e., 80.

Null Values:
The term NULL in SQL is used to specify that a data value does not exist in the database. It
is not the same as an empty string or a value of zero, and it signifies the absence of a value or
the unknown value of a data field.
Some common reasons why a value may be NULL −
 The value may not be provided during the data entry.
 The value is not yet known.
It is important to understand that you cannot use comparison operators such as “=”, “<”, or
“>” with NULL values. This is because the NULL values are unknown and could represent
any value. Instead, you must use “IS NULL” or “IS NOT NULL” operators to check if a
value is NULL.
Syntax
The basic syntax of NULL while creating a table.
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Here, NOT NULL signifies that column should always accept an explicit value of the given
data type. There are two columns where we did not use NOT NULL, which means these
columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
Let us create a table with the name CUSTOMERS in the SQL database using the CREATE
statement as shown in the query below −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Let us insert some values into the above created table using the following query −
SQL> INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)
VALUES(1, 'Ramesh', '32', 'Ahmedabad', 2000);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(2,
'Khilan', '25', 'Delhi', 1500);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(3,
'kaushik', '23', 'Kota', 2000);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(4,
'Chaitali', '25', 'Mumbai', 6500);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(5,
'Hardik','27', 'Bhopal', 8500);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(6,
'Komal', '22', 'MP', NULL);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES(7,
'Muffy', '24', 'Indore', NULL);
To verify whether the table CUSTOMERS is created or not, use the following query −
SQL> SELECT * FROM CUSTOMERS;
The table is successfully created in the database.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
IS NOT NULL Query
Now, let us try to retrieve the records present in the table that are not null using the IS NOT
NULL operator −
SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
Output
The above query would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+----------+
IS NULL Query
Let us try to retrieve the records present in the table that are null using the IS NULL operator

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE SALARY IS NULL;
Output
The above query would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | NULL |
| 7 | Muffy | 24 | Indore | NULL |
+----+----------+-----+-----------+----------+
Updating NULL values in a table
You can update the NULL values present in a table using the UPDATE statement in SQL.
To do so, you can use the IS NULL operator in your WHERE clause to select the rows with
NULL values and then set the new value using the SET keyword.
Example
Assume the previously created table and let us try to update the NULL value(s) in the present
in the table using the UPDATE statement as shown below −
SQL> UPDATE CUSTOMERS SET SALARY = 9000 WHERE SALARY IS NULL;
Output
When you execute the above query, the output is obtained as follows −
Commands completed successfully.
Verification
Let us try to verify whether the specified record(s) in the table is updated or not using the
following query −
SQL> SELECT * FROM CUSTOMERS;
On executing the above query, the output is displayed as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 9000.00 |
| 7 | Muffy | 24 | Indore | 9000.00 |
+----+----------+-----+-----------+----------+

Nested Sub queries:


A nested query is a query that has another query embedded within it. The embedded query is
called a subquery.
A subquery typically appears within the WHERE clause of a query. It can sometimes appear
in the FROM clause or HAVING clause.
Example
Let‟s learn about nested queries with the help of an example.
Find the names of employee who have regno=103
The query is as follows −
select E.ename from employee E where E.eid IN (select S.eid from salary S where
S.regno=103);
Student table
The student table is created as follows −
create table student(id number(10), name varchar2(20),classID number(10), marks
varchar2(20));
Insert into student values(1,'pinky',3,2.4);
Insert into student values(2,'bob',3,1.44);
Insert into student values(3,'Jam',1,3.24);
Insert into student values(4,'lucky',2,2.67);
Insert into student values(5,'ram',2,4.56);
select * from student;
Output
You will get the following output −

Id Name classID Marks

1 Pinky 3 2.4

2 Bob 3 1.44

3 Jam 1 3.24

4 Lucky 2 2.67

5 Ram 2 4.56

Teacher table
The teacher table is created as follows −
Example
Create table teacher(id number(10), name varchar(20), subject varchar2(10), classID
number(10), salary number(30));
Insert into teacher values(1,‟bhanu‟,‟computer‟,3,5000);
Insert into teacher values(2,'rekha','science',1,5000);
Insert into teacher values(3,'siri','social',NULL,4500);
Insert into teacher values(4,'kittu','mathsr',2,5500);
select * from teacher;
Output
You will get the following output −

Id Name Subject classID Salary

1 Bhanu Computer 3 5000

2 Rekha Science 1 5000

3 Siri Social NULL 4500

4 Kittu Maths 2 5500

Class table
The class table is created as follows −
Example
Create table class(id number(10), grade number(10), teacherID number(10), noofstudents
number(10));
insert into class values(1,8,2,20);
insert into class values(2,9,3,40);
insert into class values(3,10,1,38);
select * from class;
Output
You will get the following output −

Id Grade teacherID No.ofstudents

1 8 2 20
Id Grade teacherID No.ofstudents

2 9 3 40

3 10 1 38

Now let‟s work on nested queries


Example 1
Select AVG(noofstudents) from class where teacherID IN(
Select id from teacher
Where subject=‟science‟ OR subject=‟maths‟);

Output
You will get the following output −
20.0
Example 2
SELECT * FROM student
WHERE classID = (
SELECT id
FROM class
WHERE noofstudents = (
SELECT MAX(noofstudents)
FROM class));
Output
You will get the following output −
4|lucky |2|2.67
5|ram |2|4.56

Complex Queries:
Complex queries are often impossible to write as a single SQL block or a union / intersection
/ difference of SQL blocks. There are two ways of composing multiple SQL blocks to express
a complex query.
Derived Relations: SQL allows a subquery expression to be used in the from clause. If such
an expression is used, then the result relation must be given a name, and the attributes can be
renamed. This renaming is done using the as clause. Consider the subquery
(select branch-name, avg (balance)
from account
group by branch-name)
as result (branch-name, avg-balance)
This subquery generates a relation consisting of the names of all branches and their
corresponding average account balances. The subquery result is named result, with the
attributes branch-name and avg-balance.
The following query finds the average account balance of those branches where the average
account balance is greater then $1200.
(select branch-name, avg-balance
from (select branch-name, avg (balance)
from account
group by branch-name)
as branch-avg (branch-name, avg-balance)
where avg-balance > 1200
The subquery in the from clause computes the average balance, and it result is named as
branch-avg. The attributes of branch-avg can be used directly in the where clause.
The query shown below finds the maximum across all branches of the total balance at each
branch.
select max (tot-balance)
from (select branch-name, sum (balance)
from account group by branch-name)
as branch-total (branch-name, tot-balance)
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. Consider the
following query, which selects accounts with the maximum balance; if there are many
accounts with the same maximum balance, all of them are selected.
with max-balance (value) as
select max (balance)
from account
select account-number
from account, max-balance
where account.balance = max-balance.value
The with clause makes the query logic clearer; it also permits a view definition to be used in
multiple places within a query.
The following query is to find all branches where the total account deposit is less than the
average of the total account deposits at all branches.
with branch-total (branch-name, value) as
select branch-name, sum (balance)
from account
group by branch-name
with branch-total-avg (value) as
select avg (value)
from branch-total
select branch-name
from branch-total, branch-total-avg
where branch-total.value < branch-total-avg.value

Views:
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in
the database.
o A view can either have specific rows based on certain condition or all the
rows of a table.

Sample table: Student_Detail


STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida
3 David Ghaziabad

4 Alina Gurugram

Student_Marks
STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2.....
FROM table_name WHERE condition;
2. Creating View from a single table
Query:
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS
FROM Student_Details WHERE STU_ID < 4;
Just like table query, we can query the view to view the data. SELECT * FROM
DetailsView;
Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables

View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView: SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
1. DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
1. DROP VIEW MarksView;
Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access to a predetermined
set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring the users
to actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the base tables provided the
number of columns in view must match the number of columns specified in select statement.
Thus, renaming helps to to hide the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.

Joined relations:
Join is a combination of a Cartesian product followed by a selection process. A Join
operation pairs two tuples from different relations, if and only if a given join condition is
satisfied.
We will briefly describe various join types in the following sections.
Example:
EMPLOYEE

EMP_CODE EMP_NAME

101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

1. Operation: (EMPLOYEE ⋈ SALARY)


Result:
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

EMP_CODE EMP_NAME SALARY

101 Stephan 50000

102 Jack 30000

103 Harry 25000


Types of Join operations:

1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are equal on their
common attribute names.
o It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)
Output:

EMP_NAME SALARY

Stephan 50000

Jack 30000

Harry 25000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information.
Example:
EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000


An outer join is basically of three types:
a. Left outer join
b. Right outer join
c. Full outer join
a. Left outer join:
o Left outer join contains the set of tuples of all combinations in R and S that are equal
on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.
Example: Using the above EMPLOYEE table and FACT_WORKERS table
Input:
1. EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:


o Right outer join contains the set of tuples of all combinations in R and S that are equal
on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.
Example: Using the above EMPLOYEE table and FACT_WORKERS Relation
Input:
1. EMPLOYEE ⟖ FACT_WORKERS
Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad

Kuber HCL 30000 NULL NULL

c. Full outer join:


o Full outer join is like a left or right join except that it contains all rows from both
tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in S that
have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.
Example: Using the above EMPLOYEE table and FACT_WORKERS table
Input:
1. EMPLOYEE ⟗ FACT_WORKERS
Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched data as
per the equality condition. The equi join uses the comparison operator(=).
Example:
CUSTOMER RELATION

CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

Input:
1. CUSTOMER ⋈ PRODUCT
Output:

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

2 Harry 2 Mumbai

3 Harry 3 Noida

PL/SQL: Functions:
Function can be used as a part of SQL expression i.e. we can use them with
select/update/merge commands. One most important characteristic of a function is that,
unlike procedures, it must return a value. A function is same as a procedure except that it
returns a value. Therefore, all the discussions of the previous chapter are true for functions
too.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the function.
 function-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone function.
Example
The following example illustrates how to create and call a standalone function. This function
returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result

Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or
when the last end statement is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name and if the function returns a value, then you can store the returned value. Following
program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
PL/SQL procedure successfully completed.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45

PL/SQL procedure successfully completed.


PL/SQL Recursive Functions
We have seen that a program or subprogram may call another subprogram. When a
subprogram calls itself, it is referred to as a recursive call and the process is known
as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is
defined as −
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself recursively

DECLARE
num number;
factorial number;
FUNCTION fact(x number)
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
PL/SQL procedure successfully completed.

Procedures:
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
How to pass parameters in procedure:

When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or
function. The value of the parameter cannot be overwritten by the procedure
or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten by
the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten by
the procedure or function.

A procedure may or may not return any value.


PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section [EXCEPTION
exception_section]
END [procedure_name];
Create procedure example
In this example, we are going to insert record in user table. So you need to create user table
first.
Table creation:
create table user(id number(10) primary key,name varchar2(100)); Now write the
procedure code to insert record in user table.
Procedure Code:
create or replace procedure "INSERTUSER" (id IN NUMBER,
name IN VARCHAR2)
is begin
insert into user values(id,name); end;
/
Output:
Procedure created.
PL/SQL program to call procedure
Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul'); dbms_output.put_line('record inserted successfully');
END;
/
Now, see the "USER" table, you will see one record is inserted.
ID Name

101 Rahul

PL/SQL Drop Procedure


Syntax for drop procedure
DROP PROCEDURE procedure name;
Example of drop procedure
DROP PROCEDURE pro1;

Triggers:
Trigger: A trigger is a stored procedure in database which automatically invokes whenever a
special event in the database occurs. For example, a trigger can be invoked when a row is
inserted into a specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name] [before | after]
{insert | update | delete} on [table_name]
[for each row] [trigger_body] Explanation of syntax:

2. create trigger [trigger_name]: Creates or replaces an existing trigger with the


trigger_name.
3. [before | after]: This specifies when the trigger will be executed.
4. {insert | update | delete}: This specifies the DML operation.
5. on [table_name]: This specifies the name of the table associated with the trigger.
6. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected.
7. [trigger_body]: This provides the operation to be performed as trigger is fired
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run. AFTER
triggers run the trigger action after the triggering statement is run.
Example:
Given Student Report Database, in which student marks assessment is recorded. In such
schema, create a trigger so that the total and average of specified marks is automatically
inserted whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
mysql> desc Student;
+ -+ + -+ -+ + +
| Field | Type | Null | Key | Default | Extra |
+ -+ + -+ -+ + +
| tid | int(4) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL | |
| subj1 | int(2) | YES | | NULL | |
| subj2 | int(2) | YES | | NULL | |
| subj3 | int(2) | YES | | NULL | |
| total | int(3) | YES | | NULL | |
| per | int(3) | YES | | NULL | |
+ -+ + -+ -+ + + 7 rows in set (0.00 sec)
SQL Trigger to problem statement. create trigger stud_marks
before INSERT on
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3, Student.per = Student.total
* 60 / 100;
Above SQL statement will create a trigger in the student database in which whenever subjects
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.,
mysql> insert into Student values(0, "ABCDE", 20, 20, 20, 0, 0);
Query OK, 1 row affected (0.09 sec)
mysql> select * from Student;
+ +- + -+ +- + + +
| tid | name | subj1 | subj2 | subj3 | total | per |
+ +- + -+ +- + + +
| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |
+ +- + -+ +- + + + 1 row in set (0.00 sec)
In this way trigger can be creates and executed in the databases.
Attention reader! Don‟t stop learning now. Get hold of all the important CS Theory concepts
for SDE interviews with the CS Theory Course at a student-friendly price and become
industry ready.
Advantages of Triggers
These are the following advantages of Triggers:
o Trigger generates some derived column values automatically
o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactions Creating a trigger:
Syntax for creating trigger:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements EXCEPTION
Exception-handling-statements
END;
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an
existing trigger with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would 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.
o WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.
PL/SQL Trigger Example
Let's take a simple example to demonstrate the trigger. In this example, we are using the
following CUSTOMERS table:
Create table and have records:

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000


Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire
for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR
INSERT OR UPDATE ON customers FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary
difference: ' || sal_diff);
END;
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.

Check the salary difference by procedure:


Use the following code to get the old salary, new salary and salary difference after the trigger
created.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;/
Output:

Old salary: 20000


New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000

Note: As many times you executed this code, the old and new both salary is incremented by
5000 and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Old salary: 25000
New salary: 30000
Salary difference: 5000
Old salary: 27000
New salary: 32000
Salary difference: 5000
Old salary: 29000
New salary: 34000
Salary difference: 5000
Old salary: 31000
New salary: 36000
Salary difference: 5000
Old salary: 33000
New salary: 38000
Salary difference: 5000
Old salary: 35000
New salary: 40000
Salary difference: 5000
6 customers updated

Important Points
Following are the two very important point and should be noted carefully.OLD and NEW
references are used for record level triggers these are not avialable for table level triggers.
If you want to query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes are
applied and the table is back in a consistent state.

Cursors:
Whenever DML statements are executed, a temporary work area is created in the system
memory and it is called a cursor. A cursor can have more than one row, but processing wise
only 1 row is taken into account. Cursors are very helpful in all kinds of databases like
Oracle, SQL Server, MySQL, etc. They can be used well with DML statements like Update,
Insert and Delete. Especially Implicit cursors are there with these operations. From time to
time it changes the values and hence the implicit cursor attribute values need to be assigned
in a local variable for further use. In PL/SQL, two different types of cursors are available.
 Implicit cursors
 Explicit cursors
Explicit cursors
Explicit cursors are defined by the programmers to have more control area on the context
area. It has to be defined in the declaration section of the PL/SQL Block. Usually, It is
defined on a SELECT Statement and it returns more than one row as output. We can iterate
over the rows of data and perform the required operations.
Steps involved in creating explicit cursors:
 Cursor Declaration for initializing the memory
CURSOR <cursorName> IS
SELECT <Required fields> FROM <tableName>;
 Cursor Opening to allocate the memory
OPEN <cursorName>;
 Cursor Fetching to retrieve the data
FETCH <cursorName> INTO <Respective columns>
 Cursor Closing to release the allocated memory
CLOSE <cursorName>;
Example:
DECLARE
empId employees.EMPLOYEEID%type;
empName employees.EMPLOYEENAME%type;
empCity employees.EMPLOYEECITY%type;
CURSOR c_employees is
SELECT EMPLOYEEID, EMPLOYEENAME, EMPLOYEECITY FROM employees;
BEGIN
OPEN c_employees;
LOOP
FETCH c_employees into empId , empName , empCity;
EXIT WHEN c_employees %notfound;
dbms_output.put_line(empId || ' ' || empName || ' ' || empCity);
END LOOP;
CLOSE c_employees ;
END;
/
Output:

Implicit cursors
For DML statements, implicit cursors are available in PL/SQL i.e. no need to declare the
cursor, and even for the queries that return 1 row, implicit cursors are available. Through the
cursor attributes, we can track the information about the execution of an implicit cursor.
Attributes of Implicit Cursors:
Implicit cursor attributes provide the results about the execution of INSERT, UPDATE,
and DELETE. We have different Cursor attributes like “%FOUND”, “%ISOPEN”,
“%NOTFOUND”, and %ROWCOUNT. The most recently executed SQL statement result
will be available in Cursor. Initially cursor value will be null.
Let us see the different cursor attributes one by one with regards to the DML statements. So
let us create a sample table named “employees” in oracle:
CREATE TABLE employees
( EMPLOYEEID number(10) NOT NULL,
EMPLOYEENAME varchar2(50) NOT NULL,
EMPLOYEECITY varchar2(50)
);
Insert the records in “employees” table
INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES
(1,'XXX','CHENNAI');
INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES
(2,'XYZ','MUMBAI');
INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES
(3,'YYY','CALCUTTA');
Existence of records in “employees” table
SELECT * FROM employees;
%FOUND attribute
CREATE TABLE tempory_employee AS SELECT * FROM employees;
DECLARE
employeeNo NUMBER(4) := 2;
BEGIN
DELETE FROM tempory_employee WHERE employeeId = employeeNo ;
IF SQL%FOUND THEN -- delete succeeded
INSERT INTO tempory_employee (employeeId,employeeName,employeeCity)
VALUES (2, 'ZZZ', 'Delhi');
END IF;
END;
/

Now check for the details present in the tempory_employee table


SELECT * FROM tempory_employee;
Output:
%FOUND attribute and performing update operation example
CREATE TABLE tempory_employee1 AS SELECT * FROM employees;
DECLARE
employeeNo NUMBER(4) := 2;
BEGIN
DELETE FROM tempory_employee WHERE employeeId = employeeNo ;
IF SQL%FOUND THEN -- delete succeeded
UPDATE employees SET employeeCity = 'Chandigarh' WHERE employeeId = 1;
END IF;
END;
/
Output from SELECT * FROM employees:

%FOUND attribute upon update operation and then performing delete operation
example
CREATE TABLE tempory_employee2 AS SELECT * FROM employees;
DECLARE
employeeNo NUMBER(4) := 2;
BEGIN
UPDATE tempory_employee2 SET employeeCity = 'Gurgaon' WHERE employeeId =
employeeNo;
IF SQL%FOUND THEN -- update succeeded
DELETE FROM tempory_employee2 WHERE employeeId = 1 ; -- Then delete a
specific row
END IF;
END;
/
Output:

After doing above operations


%ISOPEN Attribute: For Implicit Cursors, always the result is False. The reason is Oracle
closes immediately after executing the DML result. Hence the result is FALSE.
%NOTFOUND Attribute: It is just the opposite of %FOUND. %NOTFOUND is the
logical opposite of %FOUND. %NOTFOUND results in TRUE value for an INSERT,
UPDATE, or DELETE statement which affected no rows. By default, it returns False.
%ROWCOUNT Attribute: A number of rows affected by an INSERT, UPDATE or
DELETE statement are given by %ROWCOUNT. When there are no rows are affected,
%ROWCOUNT gives 0 as the result, otherwise, it returns the number of rows that have been
deleted.
CREATE TABLE tempory_employee3 AS SELECT * FROM employees;
DECLARE employeeNo NUMBER(4) := 2;
BEGIN
DELETE FROM tempory_employee3 WHERE employeeId = employeeNo ;
DBMS_OUTPUT.PUT_LINE('Number of employees deleted: ' ||
TO_CHAR(SQL%ROWCOUNT));
END;
Output:
The values of the cursor attribute have to be saved in a local variable and those variables can
be used in future uses. The reason is while doing multiple database operations in different
blocks, cursor attribute values keep on changing and hence this is much required.
The %NOTFOUND attribute is better used only with DML statements but not with SELECT
INTO statement.

Embedded SQL:
SQL provides a powerful declarative query language and writing queries is usually much
easier than coding in a general-purpose programming language. However, a programmer
must have access to a database from a general-purpose programming language for at least
two reasons:
1. Not all queries can be expressed in SQL, since SQL does not provide the full
expressive power of a general-purpose language.
2. Non-declarative actions – such as printing a report, interacting with a user, or
sending the results of a query to a graphical user interface – cannot be done
from within SQL.
The SQL standard defines embeddings of SQL in a variety of programming languages, such
as C, COBOL, Pascal, Java, PL / I, and Fortran. A language in which SQL queries are
embedded is referred to as a host language, and the SQL structures permitted in the host
language constitute embedded SQL.
Programs written in the host language can use the embedded SQL syntax to access and
update data stored in a database. In embedded SQL, all query processing is performed by the
database system, which then makes the result of the query available to the program one tuple
(record) at a time.
An embedded SQL program must be processed by a special preprocessor prior to
compilation. The preprocessor replaces embedded SQL requests with host language
declarations and procedure calls that allow runtime execution of the database accesses. Then,
the resulting program is compiled by the host language compiler. To identify embedded SQL
requests to the preprocessor, the EXEC SQL statement is used; it has the form
EXEC SQL <embedded SQL statement> END-EXEC
The exact syntax for embedded SQL requests depends on the language in which SQL is
embedded. For example a semicolon is used instead of END-EXEC when SQL is embedded
in C. The Java embedding of SQL uses the syntax
# SQL { <embedded SQL statement> };
The statement SQL INCLUDE is placed in the program to identify the place where the
preprocessor should insert the special variables used for communication between the program
and the database system. Variables of the host language can be used within embedded SQL
statements, but they must be preceded by a colon (:) to distinguish them from SQL variables.
If the SQL query results in an error, the database system stores an error diagnostic in the SQL
communication-area (SQLCA) variables, whose declarations are inserted by the SQL
INCLUDE statement.
Embedded SQL allows a host-language program to access the database, but it provides no
assistance in presenting results to the user or in generating reports. Most commercial database
products include tools to assist application programmers in creating user interfaces and
formatted reports.

Query Processing:
Query Processing in DBMS

A query processor is one of the major components of a relational database or an electronic


database in which data is stored in tables of rows and columns. It complements the storage
engine, which writes and reads data to and from storage media.

Parsing and Translation


As query processing includes certain activities for data retrieval. Initially, the given user
queries get translated in high-level database languages such as SQL. It gets translated into
expressions that can be further used at the physical level of the file system. After this, the
actual evaluation of the queries and a variety of query -optimizing transformations and takes
place.
Query Evaluation Plan
o In order to fully evaluate a query, the system needs to construct a query
evaluation plan.
o The annotations in the evaluation plan may refer to the algorithms to be used
for the particular index or the specific operations.
o Such relational algebra with annotations is referred to as Evaluation
Primitives. The evaluation primitives carry the instructions needed for the
evaluation of the operation.
o Thus, a query evaluation plan defines a sequence of primitive operations used
for evaluating a query. The query evaluation plan is also referred to as the
query execution plan.
o A query execution engine is responsible for generating the output of the
given query. It takes the query execution plan, executes it, and finally makes
the output for the user query.
Optimization
o The cost of the query evaluation can vary for different types of queries.
Although the system is responsible for constructing the evaluation plan, the
user does need not to write their query efficiently.
o Usually, a database system generates an efficient query evaluation plan,
which minimizes its cost. This type of task performed by the database system
and is known as Query Optimization.
o For optimizing a query, the query optimizer should have an estimated cost
analysis of each operation. It is because the overall operation cost depends on
the memory allocations to several operations, execution costs, and so on.

Heuristics for Query Optimization:


Heuristic optimization transforms the expression-tree by using a set of rules which improve
the performance. These rules are as follows −
 Perform the SELECTION process foremost in the query. This should be the first
action for any SQL table. By doing so, we can decrease the number of records
required in the query, rather than using all the tables during the query.
 Perform all the projection as soon as achievable in the query. Somewhat like a
selection but this method helps in decreasing the number of columns in the query.
 Perform the most restrictive joins and selection operations. What this means is that
select only those sets of tables and/or views which will result in a relatively lesser
number of records and are extremely necessary in the query. Obviously any query will
execute better when tables with few records are joined.
Some systems use only heuristics and the others combine heuristics with partial cost-based
optimization.
Steps in heuristic optimization
Let‟s see the steps involve in heuristic optimization, which are explained below −
 Deconstruct the conjunctive selections into a sequence of single selection operations.
 Move the selection operations down the query tree for the earliest possible execution.
 First execute those selections and join operations which will produce smallest
relations.
 Replace the cartesian product operation followed by selection operation with join
operation.
 Deconstructive and move the tree down as far as possible.
 Identify those subtrees whose operations are pipelined.

You might also like