0% found this document useful (0 votes)
26 views24 pages

DBMS Unit 3

Uploaded by

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

DBMS Unit 3

Uploaded by

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

Unit-3

RELATIONAL ALGEBRA:
The relational is a procedural query language. It consists of a set of operations that take one or two relations
(tables) as input and produce a new relation, on the request of the user to retrieve the specific information, as
the output (result).
It gives a step by step process to obtain the result of the query. It uses operators to perform queries.
The relational algebra contains the following operations:
1) Selection
2) projection
3) union
4) Rename
5)Difference
6) Cartesian product
7)Intersection

.
The selection, projection and rename operations are called unary operations because they operate only on
one relation.
The other operations operate on pairs of relations and are therefore called binary operations.

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.


o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction

r is used for relation

p is used as a propositional logic formula which may use connectors like: AND OR and NOT. These
relational can use as relational operators like =, ≠, ≥, <, >, ≤.
For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:σ BRANCH_NAME="perryride" (LOAN)

Output:

:BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:
3. This operation shows the list of those attributes that we wish to appear in the result. Rest of the attributes
are eliminated from the table.

o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)

Where A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn


Input:∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the tuples that are either in R
or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S

A union operation must hold the following condition:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

Example:

DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes

4. Set Intersection:

o Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in
both R & S.
o It is denoted by intersection ∩.

1. Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table


Input:∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:

o Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in R but
not in S.
o It is denoted by intersection minus (-).

1. Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product

o The Cartesian product is used to combine each row in one table with each row in the other table. It is
also known as a cross product.
o It is denoted by X.

1. Notation: E X D

Example:

EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C
3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT

Output:

EMP EMP_N EMP_D DEPT DEPT_N


_ID AME EPT _NO AME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

7. Rename Operation:

The rename operation is used to rename the output relation. It is denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT relation to STUDENT1.

1. ρ(STUDENT1, STUDENT)
SQL JOINS:
Join is a query in which data is retrieved from two or more tables. A join matches from two or more tables,
based on the value of one or more columns in each table.

The join is denoted by join symbol It is a relational algebra operation which is used to combine
(join) two relations like Cartesian-product but finally removes duplicate attributes and makes the selection,
projection operation. The join operations are 3 types.
1) Inner join
1) Natural join
2) Outer join
Inner join: inner join returns the matching rows from the table that are being joined

Syntax: select * from table1 inner join table2 on table1.column=table2.column;


Ex: select * from emp e inner join dept d on e.deptno=d.deptno;

Natural join or Equi-join: Natural Join is a type of Inner join which is based on column having same name
and same datatype present in both the tables to be joined. The Natural join is a binary operation that allows
us to combine two different relations into one relation and makes the same column in two different relations
into only one-column in the resulting relation. Suppose we have relations with following schemas that
explained for natural join and for equi-join.

Customer table
Cust_id Cust_name Address City state postal_code
101 Ramesh Market center Ongole A.P 523001
102 Avinash Ram nagar Ongole A.P 523002
103 Sunil Gandh nagar Ongole A.P 523003
104 Vasanthi Anjaiah road Ongole A.P 523003
105 Krishna Mm road Ongole A.P 523003
Order table
Order_id Order_date Product_name Qty Cust_id
1001 ‟21-Apr-08‟ Xxx 5 101
1002 ‟22-Apr-08‟ Yyy 2 103
1003 „25-May-08‟ Zzz 8 101
1004 „27-May-08‟ Aaa 7 106
1005 „27-May-08‟ Bbb 3 104
A join in which the joining the condition is based on equality between values in common columns.
Common columns appear in the result table. For example, „Customer‟ and „Order‟ tables are using to apply
equi-join operation for retrieving the related rows.
SQL> SELECT CUST_ID, CUST_NAME, ADDRESS, ORDER_ID, ORDER_NAME, ORDER_DATE,
Product_NAME, qty FROM CUSTOMER, ORDER WHERE CUSTOMER.CUST_ID =
ORDER.CUST_ID;
SQL> SELECT * FROM EMP NATURAL JOIN DEPT ;
OUTER-JOIN: When tables are joined using inner join, rows which contains matching values in the join
predicate are returned. Sometimes you may want both matching and non matching rows returned for the
table are being joined. This kind of operation is known as an outer join.
An outer join is an extended from of the inner join. In this the rows in onw table having no matching rows in
the other table will also appear in the result table with nulls.
Types of outer join: 1) Left Outer-join. 2) Right Outer-join 3) Full Outer-join
LEFT OUTER JOIN : It displays all rows from left side table (i.e CUSTOMER table) and
non-matching values of right side table are not added but displays with null values. (i.e ORDER table).

Query : SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO(+);


OR
SELECT * FROM EMP E LEFT OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO;

RIGHT OUTER JOIN : It displays all rows from right side table (i.e ORDER table) and
matching values from left side table (i.e CUSTOMER table) and non-matching values of left side table are
not added but displays with null values.

SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO(+)=D.DEPTNO;


OR
SELECT * FROM EMP E RIGHT OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO;

FULL OUTER JOIN : It displays all rows when there is a match in either left or right table.Query:

SELECT C.CUST_ID, C.CUST_NAME, C.ADDRESS, O.ORDER_ID, O.ORDER_NAME,


O.ORDER_DATE, O.P_NAME, O.QTY FROM CUSTOMER C FULL OUTR JOIN ORDER O WHERE
C.CUST_ID = O.CUST_ID;
The Division ( ÷ ) Operation: The division operation is denoted by ÷, is a relational algebra operation that
creates a new relation by selecting the rows in one relation that does not match rows in another relation.
Let relation A is ( x1 , x2, x3, . . . . xm, y1, y2, . . . , ym ) and relation B is (y1, y2, . . . , ym)
Where y1, y2, . . . , ym tuples are common to the both relation A and B with same domain compulsory. Then
A ÷ B = new relation with (x1 , x2, x3,..........xm) tuples.
Relation A and B represent the dividend and divisor respectively.
A tuple „t‟ is in a † b if and only if two conditions are satisfied,
1.t is in π(A - B) (r) .
2. For every tuple tb in B, there is a tuple ta in A satisfying the following two things.
i) ta [B] = tb [B] ii) ta [A – B] = t

Ex:A B1 A/B1

B2 A/B2

RELATIONAL CALCULUS : Relational calculus is an alternative to relational algebra. In contrast to the


algebra, which is procedural, the relational calculus is non-procedural or declarative because in that it
allows us to describe the set of answers without showing procedure about how they should be computed.
Relational calculus has a big influence on the design of commercial query languages such SQL and
especially, Query-by Example(QBE).
Relational calculus is of two types,
1. Tuple Relational Calculus (TRC).
2. Domain Relational Calculus (DRC).

Tuple Relational Calculus (TRC): The tuple relational calculus is a non-procedural qery language because
it vies the desired information without showing procedure about how they should be computed.
A query in tuple relational calculus is expressed as {T|p(T)}
where, T  tuple variable, p(T)  „p‟ is a condition or formula that is true for „t‟
In addition to that we use,
T[A]  to denote the value of tuple t on attribute A and
t є r  to denote that tuple t is in relation r.
Syntax of TRC Queries:
Let „rel‟ be a relation name, „R‟ and „S‟ be tuple variables, „a‟ is an attribute of R. „b‟ is an attribute of S.
Let „op‟ denote an operator in the set. { < , > , = , >= , <= , ≠ }
Then, an atomic formula is one of the following.

1) R є Rel. 2) R.a op S.b.


R.a op constant, or constant op R.a.
A formula is recursively defined to be one of the following, where „p‟ and „q‟ are themselves
formulas and „p(R)‟ denotes a formula in which the variable R appears,
1) any atomic formula,
2) ¬p, p ^ q, p v q or p ==> q
3) Э R (p(R)), where R is a tuple variable,
4) V R(p(R)), where R is a tuple variable.
In the last two clauses above, the quantifiers Э and V are said to be the variable R.

Semantics of TRC Queries : The TRC query { T|p(T) } is the set of all tuples „t‟ for which the formula p(T)
evaluates to true with variable T assigned the tuple value t. To complete this definition, we must state which
assignments of tuple values to the free variables in a formula make the formula evaluates to true.
A query is evaluated on a given instance of the database. Let each free variable in a formula F be
bound to a tuple value. For the given assignment of tuples to variables, with respect to the given database
instance, F evaluates to true if one of the following condition is true.
1) F is an atomic formula R є Rel and R is assigned a tuple in the instance of relation Rel.
2) F is a comparision R.a op S.b, R.a op constant, or constant op R.a and the tuples assigned to R and S
have filed values R.a and S.b that make the comparison true.
3) F is of the form ¬p and p is not true, or of the form p ^ q and both p and q are true, or of the form p v q
and one of them is true, or of the form p ==> q and q is true whenever p is true.
4) F is of the form ЭR (p(R ) and there is some assignment of tuples to the free variables in p(R ), including
the variable R, that makes the formula p(R ) true.
5) F is of the form ) V R(p(R)) and there is some assignment of tupes to the free variables in p(R ) that
makes the formula p(R ) true no matter what tuple is assigned R.

Domain Relational Calculus (DRC): A domain variable that comes in the range of the values of domain
(data types) of some columns (attributes).
Syntax of DRC Queries: Let „op‟ denote an operator in the set { < , > , = , >= , <= , ≠ } and let x and y be
domain variables.
An atomic formula in DRC is one of the following,
1) < x1 , x2, x3,..........xn > є Rel, where Rel is a relation with n attributes, each xi , 1 ≤ i ≤ n is either a variable
or a constant.
2) x op y
3) x op constant, or constant op x:
A formula is recursively defined to be one of the following, where p and q are themselves formulas
and each p(x) denotes a formula in which the variable x appears.

1) any atomic
formula,
2) ¬p, p ^ q, p v q or p ==> q
3) Э R (p(x)), where x is domain variable,
4) V R(p(x)), where x is a domain variable.
The reader can remember these formulas very easily by comparing them with TRC formulas and see
how closely these two formulas correspond.
SCHEMA DEFINITIONS IN SQL:
The schema is collection of related objects which are created by user with create command such as
tables, views, domains, constraints, character sets, triggers, roles etc., In simple way, schema is nothing but
plan how to store the data on secondary storage device and how to extract the from secondary storage
device.

SQL Commands are used to define the definition to Schema by using DDL commands,
Data Definition Language Commands (DDL) : The DDL Commands are used to define database table in
schema. It includes create, alter, drop the tables and establishing constraints. These commands are restricted
to production version database.

CREATING THE TABLES: The tables are created in SQL by CREATE command. The CREATE
command is used to create a table with column_names. The column_name are called variables or field
names. To create a table, must follow the below steps.
1. Identify the appropriate data type, including length, precision, and scale for each attribute if required.
2. Identify the columns that should accept null values.
3. Identify the columns that need to be unique.
4. Identify the primary key and foreign key for attributes.
5. Determine the values to be inserted in any column for which a default value is specified.
6. Identify any column for which domain specifications may be stated. Eg: CHECK
Create index using existed table.
Syntax: CREATE TABLE table_name(column_name1 data type1 [<constraint_type
attribute_ name>], column_name2 data type2 [<constraint_type attribute_ name>]
[CONSTRAINT constraint_name] );
 The table_name is name of table to store the data in secondary memory.
 The column_name is name of filed name, used to store the data.
 The data type is used to define column_name to store related data. The data types are number(),
char(), varchar2() and date.
 The constraint_types are used with column_name to specify the constraint type. They are i) PRIMARY
KEY, ii)FOREIN KEY, iii) UNIQUE KEY iv) REFERENCE v)NOT NULL vi) CHECK.

Eg: CREATE TABLE student(sno number(5),sname char(20), fname char(20),fee


number(7,2),date_of_join date);

Performing the operations on table definitions: Once the table is created, the user can perform operations
on table. They are adding the coulmn_names, change the size of column_name, and can remove the
column_name and table. These operations are done by using ALTER command, DESC command, DROP
command etc.

ALTER command: The ALTER command is used to change the definition of a table.
ADD
Syntax: ALTER TABLE table name MODIFY (column_name data type(size));
DROP
RENAME
ADD clause : The ADD is a keyword, used to add a column_name and/or constraints to an existing table.
Syntax : ALTER TABLE table_name ADD(new column_name data type);
Eg: ALTER TABLE student ADD(date_of_join date);

MODIFY clause : The MODIFY is a keyword, used to modify the definition of an existing column_name.
The MODIFY keyword in the ALTER command cannot make following three changes. They are
i) can not change the specification of column_name from NULL to NOT NULL when column_name
containing nulls.
ii)can not decrease the size of a column_name (or) data type when column_name contain a data.
iii)can not define constraints on a column_name except NULL/NOT NULL.

Ex: alter table student modify sno number(4);

DROP clause : It is used with ALTER command to remove a constrained from a


table. Syntax : ALTER TABLE table_name DROP constraint constraint_name;
Eg: ALTER TABLE emp DROP constraint PK;

RENAME clause: it is used to rename the column name


Syntax: alter table table_name rename column old column name to new column name;
Ex: alter table student rename column date_of_join to doj;

DESC command : This command is used to display the definition of an existed table. I.e., it will display
the structure of specified table.
Syntax : DESC table_name; Eg: DESC student;

DROP command: This command is used to delete the table name from the secondary memory.
Syntax : DROP TABLE table_name; Eg: DROP TABLE student;

RENAME command: This command is used to change the name of the table definition.
Syntax : RENAME old name TO new name;
Eg : RENAME student TO student_table;
QUERIES , TRIGGERS & CONSTRAINTS:

Introduction to SQL: SQL stands for Structured Query Language. It is the most widely used commercial
relational database language. There are numerous versions of SQL. The original SQL version was developed
at IBM‟s San Jose Research Laboratory, California in 1970. This was originally called as Sequel Language
of system R project in the early 1970‟s. The sequel was renamed as SQL during the years 1974 to 1979. The
SQL is a combination of relational algebra and relational calculus. This was a run under the DOS operating
system in 1981. The SQL language was announced as the MVS version, called DB2 in 1983.
In 1986, the ANSI/ISO published a SQL standard, called SQL-86. IBM published its own corporate
SQL standard, called the System Application Architecture database interface (SAA-SQL) in 1987. An
extended standard of SQL was published in 1989 by ANSI/ISO. The Next versions of ANSI/ISO are SQL-
92,SQL-94,SQL-96, and SQL-99. Some Other Organizations developed Relational Data Base Software‟s,
called INGRES, SYBASE etc.
In the DBMS, SQL can create the tables, translate user requests, maintain the data dictionary,
maintain the system catalog, update and maintain the tables, establish security and carry out backup and
recovery procedures.

The SQL language has several parts


The Data Manipulation Language (DML): This subset of SQL allows users to pose queries and to insert,
delete, and modify rows. Queries are the main focus of this chapter. We covered DML commands to insert,
delete, and modify rows.
The Data Definition Language (DDL): This subset of SQL supports the creation, deletion, and
modification of definitions for tables and views. Integrity constraints can be defined on tables, either when
the table is created or later. Although the standard does not discuss indexes, commercial implementations
also provide commands for creating and deleting indexes.
Triggers and Advanced Integrity Constraints: The new SQL: 1999 standard includes support for triggers,
which are actions executed by the DBMS whenever changes to the database meet conditions specified in the
trigger
Embedded and Dynamic SQL: Embedded SQL features allow SQL code to be called from a host language
such as C or COBOL. Dynamic SQL features allow a query to be constructed (and executed) at run-time.
Client-Server Execution and Remote Database Access: These commands control how a client
application program can connect to an SQL database server, or access data from a database over a network.
Transaction Management: Various commands allow a user to explicitly control aspects of how a
transaction is to be executed.
Security: SQL provides mechanisms to control users' access to data objects such as tables and views.
Advanced features: The SQL: 1999 standard includes object-oriented features, recursive queries, decision
support queries, and also addresses emerging areas such as data mining, spatial data, and text and XML
data management.

Role of SQL in Database Architecture :


A SQL based Relational database application is used to interface with a user to create the tables in
database and maintain the data using different queries such as Enter the data, update the data, retrieve the
data and carry out backup and recovery procedures.
A relational DBMS (RDBMS) is a data management system that manages data as a collection of
tables in which all data relationships are represented by common values in related tables.
The SQL standards: The SQL standards are used
1. To specify the syntax and semantics of SQL data definition and data manipulation language commands.
2. To define the data structures and basic operations for designing, accessing, maintaining, controlling and
protecting an SQL database.
3. To provide portability of database definitions (Tables) and application modules between different
DBMS.
4. To specify both Level 1 and Level 2 standards. I.e., simple and complex queries.
5. To provides an initial standards for handling integrity, transaction management, user-defined functions,
join operators, set operators, etc.

SQL Benefits or Advantages : The benefits of relational language include the following. They are
1. Reduced training costs: This reduces the training costs in organization.
2. Productivity: The user can learn SQL language thoroughly and become proficient. The programmers
also write the programs and quickly maintain existing programs in SQL.
3. Application Portability: Applications can be easily moved from machine to machine and can develop
the standards.
4. Application longevity: The old applications developed in SQL old versions can be developed using the
advanced SQL do not taking a long time.
5. Reduced dependence on a single vendor: The learners can get assistance, training and educational
services from the vendors. Because, the SQL is easy language. So user does not depend on single person.
[i.e., more vendors are available to give the assistance].
6. Cross-system communication: Different DBMSs and application programs can more easily
communicate and co-operate in managing data and processing user programs.

THE FORM OF A BASIC SQL QUERY


The syntax of a simple SQL query and explains its meaning through a conceptual Evaluation
strategy. A conceptual evaluation strategy is a way to evaluate the query that is intended to be easy to
understand rather than efficient. A DBMS would typically execute a query in a different and more efficient
way.
The basic form of an SQL query is as follows:
SELECT [DISTINCT] select-list
FROM from-list
WHERE qualification
Every query must have a SELECT clause, which specifies columns to be retained in the result, and a
FROM clause, which specifies a cross-product of tables. The optional WHERE clause specifies selection
conditions on the tables mentioned in the FROM clause.
Such a query intuitively corresponds to a relational algebra expression involving selections,
projections, and cross-products. The close relationship between SQL and relational algebra is the basis for
query optimization in a relational DBMS, as we will see in Chapters 12 and 15. Indeed, execution plans for
SQL queries are represented using a variation of relational algebra expressions

we will present a number of sample queries using the following table definitions:
Sailors( sid: integer, sname: string, rating: integer, age: real)
Boats( bid: integer, bname: string, color: string)
Reserves (sid: integer, bid: integer, day: date)

Create the sailors Table:


CREATE TABLE sailors ( sid number(3),sname varchar2(12),rating number(2),age number(3,1),
CONSTRAINT PK_sailors PRIMARY KEY (sid) );
Create the boats Table:
CREATE TABLE boats(bid number(3) primary key,bname varchar2(12),color varchar2(10);
Create the reserves Table:
CREATE TABLE reserves ( sid number(3),bid number(3),day date,
CONSTRAINT PK_reserves PRIMARY KEY (sid, bid, day),
FOREIGN KEY (sid) REFERENCES sailors(sid),
FOREIGN KEY (bid) REFERENCES boats(bid) );

EX: Find all sailors with a rating above 7.

SQL>SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7
This query uses the optional keyword AS to introduce a range variable. Incidentally, when we want
to retrieve all columns, as in this query, SQL provides convenient shorthand: we can simply write SELECT
*. This notation is useful for interactive querying, but it is poor style for queries that are intended to be
reused and maintained because the schema of the result is not clear from the query itself; we have to refer to
the schema of the underlying Sailors table.

Now we consider the syntax of a basic SQL query in more detail.


• The from-list in the FROM clause is a list of table names. A table name can be followed by a range
variable; a range variable is particularly useful when the same table name appears more than once in the
from-list.
• The select-list is a list of (expressions involving) column names of tables named in the from-list. Column
names can be prefixed by a range variable.
• The qualification in the WHERE clause is a Boolean combination (i.e., an expression using the logical
connectives AND, OR, and NOT) of conditions of the form expression op expression, where op is one of
the comparison operators {<, <=, =, <>, >=, >}.2 An expression is a column name, a constant, or an
(arithmetic or string) expression.
• The DISTINCT keyword is optional. It indicates that the table computed as an answer to this query should
not contain duplicates, that is, two copies of the same row. The default is that duplicates are not eliminated.
The syntax of a basic SQL query, they do not tell us the meaning of a query. The answer to a query is itself a
relation which is a multi set of rows in SQL considering the following conceptual evaluation strategy:
1. Compute the cross-product of the tables in the from-list.
2. Delete rows in the cross-product that fail the qualification conditions.
3. Delete all columns that do not appear in the select-list.
4. If DISTINCT is specified, eliminate duplicate rows.

UNION, INTERSECT AND EXCEPT


SQL provides three set-manipulation constructs that extend the basic query it is natural to consider the use
of operations such as union, intersection, and difference. SQL supports these operations under the names
UNION, INTERSECT, and EXCEPT.
SQL also provides other set operations: IN (to check if an elementis in a given set), op ANY, op ALL (to
compare a value with the elements in a given set, using comparison operator op), and EXISTS (to
check if a set is empty). IN and EXISTS can be prefixed by NOT, with the obvious modification to their
meaning.
Ex: Find the names of sailors who have reserved a red or a green boat
SQL>SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid
AND B.color = „red‟ UNION SELECT S1.sname FROM Sailors S1, Boats B1, Reserves R1 WHERE
S1.sid = R1.sid AND R1.bid = B1.bid AND B1.color = 'green';

Ex: Find the names of sailor's who have reserved both a red and a green boats.
SQL>SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid
AND B.color = „red‟ INTERSECT SELECT S1.sname FROM Sailors S1, Boats B1, Reserves R1 WHERE
S1.sid = R1.sid AND R1.bid = B1.bid AND B1.color = 'green';

Ex: Find the sids of all sailor's who have reserved red boats but not green boats.
SQL>SELECT S.sid FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid
AND B.color = „red‟ EXCEPT SELECT S1.sid FROM Sailors S1, Boats B1, Reserves R1 WHERE S1.sid
= R1.sid AND R1.bid = B1.bid AND B1.color = 'green';
Sailors 22, 64, and 31 have reserved red boats. Sailors 22, 74, and 31 have reserved green boats. Hence, the
answer contains just the sid 64.

NESTED QUERIES:
A Sub query or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.
A sub query is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.
Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that sub queries must follow
 Sub queries must be enclosed within parentheses.
 A sub query can have only one column in the SELECT clause, unless multiple columns are in the
main query for the sub query to compare its selected columns.
 An ORDER BY command cannot be used in a sub query, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER
BY in a sub query.
 Sub queries that return more than one row can only be used with multiple value operators such as
the IN operator.
 A sub query cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a sub query. However, the BETWEEN operator
can be used within the sub query.

Syntax of nested query:


SELECT column_name [,column_name]
FROM table1 [,table2]
WHERE column_name OPERATOR
(SELECT column_name [,column_name]
FROM table1 [,table2]
WHERE condition);
Ex: Find the names of sailors who have reserved boat 103.
SQL>SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R
WHERE R.bid = 103 );
The nested sub query computes the (multi)set of sids for sailors who have reserved boat 103 (the set contains
22,31, and 74) and the top-level query retrieves the names of sailors whose sid is in this set. The IN operator
allows us to test whether a value is in a given set of elements;
CORRELATED NESTED QUERIES:
In the nested queries the inner sub query has been completely independent of the outer query. In eneral, the
inner sub query could depend on the row currently being examined in the outer query.
Ex: Find the names of sailors who have reserved boat number 103.
SQL>SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE
R.bid = 103 AND R.sid = S.sid );
The EXISTS operator is another set comparison operator, such as IN. It allows us to test whether a
set is nonempty, an implicit comparison with the empty set.
This query also illustrates the use of the special symbol * in situations where all we want to do is to
check that a qualifying row exists, and do Hot really want to retrieve any columns from the row. This is one
of the two uses of * in the SELECT clause that is good programming style; the other is as an argument of the
COUNT aggregate operation. by using NOT EXISTS instead of EXISTS, we can compute the names of
sailors who have not reserved a red boat. Closely related to EXISTS is the UNIQUE predicate.

Set-Comparison Operators:
The set-comparison operators EXIST, IN, and UNIQUE, along with their negated versions. SQL also
supports op ANY and op ALL, where operator is one of the arithmetic comparison operators {<, <=, =,
<>, >=, >}.
Ex: Find sailors whose rating is better than some sailor called Horatio.
SELECT S.sid FROM Sailors S WHERE S.rating > ANY (SELECT S2.rating FROM Sailors S2
WHERE S2.sname = „Horatio‟);
If there are several sailors called Horatio, this query finds all sailors whose ratingis better than that of
some sailor called Horatio. On instance sailors this computes the sids 31, 32, 58, 71, and 74.
Ex: Find sailors whose rating is better than every sailor' called Horatio.
SQL> SELECT S.sid FROM Sailors S WHERE S.rating > ALL (SELECT S2.rating FROM Sailors S2
WHERE S2.sname = „Horatio‟);
On instance sailors we would get the sid", 58 and 71

AGGREGATE OPERATORS:
To simply retrieving data we often want to perform some computation or summarization. SQL
allows the use of arithmetic expressions. We now consider a powerful class of constructs for computing
aggregate values such as MIN and SUM. These features represent a significant extension of relational
algebra. SQL supports five aggregate operations, which can be applied on any column.

1. COUNT ([DISTINCT] A): The number of (unique) values in the A column.


Ex: Count the number of sailors.
SQL>select count(*) from sailors;

Ex: Count the number of different sailor names.


SQL>select count(distinct sname) from sailors;

2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
Ex: sum the rating of all sailors;
SQL>select sum(rating) from sailors;

3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
Ex: Average age of all sailors.
SQL> select avg(age) from sailors;
4. MAX (A): The maximum value in the A column.
Ex: Maximum rating of sailors.
SQL>select max(rating) from sailors;
5. MIN (A): The minimum value in the A column.
Ex: Minimum rating of sailors.
SQL>select min(rating) from sailors;

The Group By And Having Clauses:


GROUP BY clause : This clause is used in SELECT command to group the rows of specified table which
column has same values and display only one name for each group. It is most useful for aggregate functions
such as sum(), avg(), count() etc.,

Syntax : SELECT column_name [, aggregate name] FROM <table name> [WHERE <condition>]
GROUP BY column_name;
 The „column_name‟ of SELECT command and which used in GROUP BY clause must be same.
 The <table name> is name of table.
 The aggregate name is any function such as sum(), avg() etc., Eg:
1) Find the age of the youngest sailor for each rating level.
SQL> select sname,min(age) from sailors group by rating;
 It will display only one sailors name and age for each rating group
Eg: 2) Find the age of the youngest sailor who is eligible to vote (i.e., is at least 18 years old) for each
rating level with at least h.uo such sailors.
SQL> SELECT S.rating, MIN (S.age) AS minage FROM Sailors S WHERE S.age >= 18 GROUP BY
S.rating HAVING COUNT (*) > 1;

HAVING clause : This clause is used in SELECT command and it is similar to WHERE clause, but it
identifies groups which match in a specified condition.

Syntax : SELECT column_name [, aggregate name] FROM <table name> [WHERE <condition>] GROUP
BY column_name HAVING <condition>;
 The „column_name‟ of SELECT command and which used in GROUP BY clause must be same.
 The <table name> is name of table.
 The aggregate name is any function such as sum(), avg() etc.,
 The HAVING < condition> contains relational expression and one of the column must be
Aggregate function.

Eg: 1) SELECT JOB FROM EMP GROUP BY JOB HAVING AVG(SAL) > 3000;
 It will display only one job name for each group and whose employee average salary is > 3000.

Eg: 2) SELECT AVG(SAL), JOB FROM EMP GROUP BY JOB HAVING MAX(SAL) > 3000;
 It will display only one job name, and average salary for each group and whose maximum salary > 3000.

NULL VALUES:
SQL provides a special column value called null to use in such situations. We use null when the column
value is either unknown or inapplicable. Using the Sailor table definition, we might enter the row (98. Dan,
null, 39). The presence of null values complicates many issues these issues are
 Comparisons using null values
 Logical connectivity AND, OR and NOT
 Impact on SQL construct
 Outer joins
 Disallowing Null Values
Comparisons using null values:
SQL also provides a special comparison operator IS NULL to test whether a column value is null; for
example, we can say rating IS NULL, which would evaluate to true on the row representing Dan. We can
also say rating IS NOT NULL, which would evaluate to false on the row for Dan.

SQL> select * from sailors where rating is null;

Logical connectivity AND, OR and NOT:


Boolean expressions such as rating = 8 OR age < 40 and rating = 8 AND age < 40? Considering the
row for Dan again, because age < 40, the first expression evaluates to true regardless of the value of rating,
but what about the second? We can only say unknown
We must define the logical operators AND, OR, and NOT using a three-valued logic in which
expressions evaluate to true, false, or unknown. We extend the use interpretations of AND, OR, and NOT to
cover the case when one of the arguments is unknown as follows. The expression NOT unknown is defined
to be unknown. OR of two arguments evaluates to true if either argument evaluates to true, and to unknown
if one argument evaluates to false and the other evaluates to unknown. (If both arguments are false, of
course, OR evaluates to false.) AND of two arguments evaluates to false if either argument evaluates to
false, and to unknown if one argument evaluates to unknown and the other evaluates to true or unknown. (If
both arguments are true, AND evaluates to true.)

Impact on SQL construct:


the arithmetic operations +, -, *, and / all return null if one of their arguments is null. However, nulls
can cause some unexpected behavior with aggregate operations. COUNT(*) handles 'null values just like
other values; that is, they get counted. All the other aggregate operations (COUNT, SUM, AVG, MIN,
MAX, and variations using DISTINCT) simply discard null values

Outer Joins:
Interesting variants of the join operation that rely on null values, called outer joins, are supported in
SQL. Consider the join of two tables, say Sailors Reserves. Tuples of Sailors that do not
match some row in Reserves according to the join condition do not appear in the result. In an outer join, on
the other , Sailor rows without a matching Reserves row appear exactly once in the result, with the result
columns inherited from Reserves assigned null values.
In a left outer join,
Sailor rows without a matching Reserves row appear in the result but not vice versa. In a right outer
join, Reserves rows without a matching Sailors row appear in the result, but not vice versa. In a full outer
join, both Sailors and Reserves rows without a match appear in the result.

SQL allows the desired type of join to be specified in the FROM clause. For example, the following
query lists
SQL>SELECT S.sid, R.bid FROM Sailors S LEFT OUTER JOIN Reserves R on s.sid=r.sid;

Disallowing null values:


Sql also provides one constraint not null, disallow null values by specifying NOT NULL as part of the field
definition for example, sname CHAR(20) NOT NULL. In addition, the fields in a primary key are not
allowed to take on null values. Thus, there is an implicit NOT NULL constraint for every field listed in a
PRIMARY KEY constraint.

COMPLEX INTEGRITY CONSTRAINTS IN SQL:


complex integrity constraints that utilize the full power of SQL queries, complement the integrity constraint
provides several features. These features are
 Constraints over a single table
 Domain constraints and distinct types
 Assertions: ics over several tables

Constraints over a single table:


Complex constraints over a single table using table constraints, which have the form CHECK conditional-
expression. For example, to ensure that rating must be an integer in the range 1 to 10, we could use
CREATE TABLE Sailors ( sid number(3),
sname CHAR(10),
rating number(3),
age number(3,1),
PRIMARY KEY (sid),
CHECK (rating >= 1 AND rating <= 10 ));

Domain constraints and distinct types:


A user can define a new domain using the CREATE DOMAIN statement, which uses CHECK
constraints
CREATE DOMAIN ratingval INTEGER DEFAULT 1 CHECK ( VALUE >= 1 AND VALUE <= 10 )

INTEGER is the underlying, or source, type for the domain ratingval, and every ratingval value must
be of this type. Values in ratingval are further restricted by using a CHECK constraint; in defining this
constraint, we use the keyword VALUE to refer to a value in the domain. By using this facility, we can
constrain the values that belong to a domain using the full power of SQL queries. Once a domain is defined,
the name of the domain can be used to restrict column values in a table.
The optional DEFAULT keyword is used to associate a default value with a domain. If the domain
ratingval is used for a column in some relation and no value is entered for this column in an inserted tuple,
the default value 1 associated with ratingval is used.

Assertions: ICs over several tables:


Table constraints are associated with a single table, although the conditional expression in the
CHECK clause can refer to other tables. Table constraints are required to hold only if the associated
table is nonempty. When a constraint involves two or more tables, To cover such situations, SqL
supports the creation of assertions, which are constraints not associated with anyone table.
As an example, suppose that we wish to enforce the constraint that the number of boats plus the number of
sailors should be less than 100.

CREATE ASSERTION smallClub CHECK (( SELECT COUNT (S.sid) FROM Sailors S )


+ ( SELECT COUNT (B. bid) FROM Boats B)< 100 );

TRIGGERS AND ACTIVE DATABASES:


A trigger is a procedure that is automatically invoked by the DBMS in response to specified changes
to the database, and is typically specified by the DBA. A database that has a set of associated triggers is
called an active database. A trigger description contains three parts:
 Event: A change to the database that activates the trigger.
 Condition: A query or test that is run when the trigger is activated.
 Action: A procedure that is executed when the trigger is activated and its condition is true.

A trigger can be thought of as a 'daemon' that monitors a database, and is executed when the
database is modified in a way that matches the event specification. An insert, delete, or update statement
could activate a trigger, regardless of which user or application invoked the activating statement; users may
not even be aware that a trigger was executed as a side effect of their program.
A condition in a trigger can be a true/false statement (e.g., all employee salaries are less than
$100,000) or a query. A query is interpreted as true if the answer set is nonempty and false if the query has
no answers. If the condition part evaluates to true, the action associated with the trigger is executed

for example, we have to examine the age field of the inserted Students record to decide whether to
increment the count.

CREATE TRIGGER inc_count BEFORE INSERT ON Students * Event *


DECLARE
count INTEGER;
BEGIN * Action *
count := 0:
END;

CREATE TRIGGER inc_count AFTER INSERT ON Students * Event *


WHEN (new.age < 18) * Condition; 'new' is just-inserted tuple *
FOR EACH ROW
BEGIN * Action; a procedure in Oracle's PL/SQL syntax *
Count := count + 1;
END;
Trigger event should be defined to occur for each modified record; the FOR EACH ROW clause is
used to do this. Such a trigger is called a row-level trigger. On the other hand, the inc_count trigger is
executed just once per INSERT statement, regardless of the number of records inserted, because we have
omitted the FOR EACH ROW phrase. Such a trigger is called a statement-level trigger.

The keyword new refers to the newly inserted tuple. If an existing tuple were modified, the keywords
old and new could be used to refer to the values before and after the modification.

Ex: Create the Before insert row level trigger


Create or replace trigger trgbir
before
insert on student for each row
begin
:new.sname := upper(:new.sname);
end;

Create the After delete statement level trigger


create or replace trigger trgads
after
delete on student
begin
raise_application_error(-20015,'you cannot delete this row');
end;
SQL operators : The SQL operators are used to perform the operation on values of columns. The SQL
operators are four types. They are 1) Arithmetic operators
2) Relational operators 3) Logical operators 4) Special operators.

1) Arithmetic operators : The Arithmetic operators are used to link the two operands for getting a new
results. The Arithmetic operators are Addition(+), Subtraction(-) multiplication (*), division (/), and
modulo (%).
Eg 1 : SELECT emp_no, emp_name, sal+hra FROM emp;
It will display emp number, employee name and sal with adding hra from emp table. Eg 2
: SELECT emp_no, emp_name, sal - tax FROM emp;
It will display emp number, employee name and sal by subtracting tax from emp table.
Eg 3 : SELECT emp_no, emp_name, sal * 12 / 100 FROM emp;

2) Relational operators : The Relational operators are used to compare two operands for further process.
The Relational operators are

Operator Meaning
> greater than
< less than
>= greater than or equal to
<= less than or equal to
= equal to
<> not equal to

Eg 1 : SELECT *FROM emp WHERE emp_no >=10;


It will display rows of data which emp_no is greater than or equal to 10.
Eg 2 : SELECT *FROM emp WHERE emp_no <=10;
It will display rows of data which emp_no is less than or equal to 10.
Eg 3 : SELECT *FROM emp WHERE emp_no < > 10;
It will display rows of data which emp_no is not equal to 10.

3) Logical operators : The Logical operators are used to compare two relational expressions. The Logical
operators are AND, OR, and NOT operators.

Eg 1 : SELECT *FROM emp WHERE emp_no >= 10 AND emp_no <= 20; It
will display rows of data which emp_no are in between 10 and 20.
Eg 2 : SELECT *FROM emp WHERE emp_no >=10 or sal = 4500;
It will display rows of data which emp_no is greater than or equal to 10 or which sal is equal to
4500.

4) Special operators : The special operators are used to match the values in given list.
The special operators are
a) BETWEEN operator b) IN/NOT IN operator
c) LIKE operator d) IS NULL operator

a) BETWEEN operator : This operator is used to match the particular column values in the given
range. The range consists lowest value and highest value.
Syntax : BETWEEN low value AND high value ;
Eg: 1 SELECT *FROM emp WHERE emp_no BETWEEN 5 AND 10;
It will display the rows of data from emp table which employee number in between 5 and 10.
Eg: 2 SELECT *FROM emp WHERE sal BETWEEN 5000 AND 10000;
It will display the rows of data from emp table which employee salary is in between 5000 and
10000.

b) i) IN operator: The IN operator is used in where clause to match the values of column in the
given list.
Syntax: IN (list)

Eg: 1 SELECT *FROM emp WHERE emp_no IN (5,6,7);


It retrieve the rows/records from emp table which emp_no will match in the list. Eg:
2 SELECT *FROM emp WHERE emp_name IN („vasu‟,‟anil‟,‟ssn‟);
It retrieve rows/records from emp table which emp_name will match in the list.

b) ii) NOT IN operator: The NOT IN operator is used in where clause to which column values are not
match in the given list.
Syntax: NOT IN (list)

Eg: 1 SELECT *FROM emp WHERE emp_no NOT IN (5,6,7);


It will display the rows of data from emp table which emp_no is not matched in the list.
Eg: 2 SELECT *FROM emp WHERE emp_name NOT IN („vasu‟,‟anil‟,‟ssn‟);
It will display the rows of data from emp table which emp_name is not matching in the list.

c) LIKE operator: The LIKE operator is used in where clause to match the possible values in the given
list. I.e. it is possible to select rows that match a character pattern. The character pattern matching
operation may be referred to as „wild-card‟ search. The symbols can be used to construct the search
string.

Syntax: LIKE „symbol‟;


The Symbols are % and - (hyphen). The % symbol represents any sequence of zero or more
characters and - (hyphen) represents any single character.
Eg: SELECT *FROM emp WHERE empname LIKE „a%‟;
It will display the rows of data from emp table which employee name starts with letter a.
Eg: SELECT *FROM emp WHERE empname LIKE „------‟;
It will display the rows of data from emp table which employee name contain four letter data..

d) IS NULL operator: The IS NULL operator is used in where clause to test the NULL value in the
given column name.
Eg: SELECT * FROM emp WHERE hra IS NULL;
It will display the rows of data from emp table which hra value is null value.

You might also like