Unit-2 Notes
Unit-2 Notes
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.
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));
Syntax:
DROP TABLE table_name;
Example:
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 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.
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;
The following example uses a single-line comment to ignore the end of a line:
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.
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.
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:
(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
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
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 |
+----+----------+-----+-----------+----------+
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 −
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 −
1 8 2 20
Id Grade teacherID No.ofstudents
2 9 3 40
3 10 1 38
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.
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
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;
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. 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
FACT_WORKERS
Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:
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:
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
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.
101 Rahul
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:
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;
/
%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:
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