Relational Algebra
 Relational Algebra is procedural query language, which
takes Relation as input and generate relation as output.
 Relational algebra mainly provides theoretical
foundation for relational databases and SQL.
 It is used in the design of transactions and forms the
conceptual basis for SQL
 It consists of operators and manipulators which apply
to relations and given relation as a result but do not
change the actual relation in DB.
The main purpose of using Relational Algebra is to define
operators that transform one or more input relations into
an output relation.
Slide No:L6-6
Selection

rating  8
(S2)
 sname,rating
 rating  8
S
( (
2))
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
sid sname rating age
28
58
yuppy
rusty
9
10
35.0
35.0
sname rating
yuppy
rusty
9
10
Slide No:L6-5

sname,rating(S2)
age
35.0
55.5

age(S2)
Projection
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
sname rating
yuppy 9
lubber 8
guppy 5
rusty 10
Joins
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.
Outer join:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
OUTER JOINS
• In an outer join, along with tuples that satisfy the matching criteria,
we also include some or all tuples that do not match the criteria.
• Left Outer Join:
• in the left outer join, operation allows keeping all tuple in the left
relation.
• However, if there is no matching tuple is found in right relation, then
the attributes of right relation in the join result are filled with null
values.
Consider the following 2 Tables
A
Num Square
2 4
3 9
4 16
B
Num Cube
2 8
3 18
5 75
A B
A B
⋈
Num Square Cube
2 4 8
3 9 18
4 16 –
OUTER JOINS
Right Outer Join: ( A B )
• In the right outer join, operation allows keeping all tuple in the
right relation.
• However, if there is no matching tuple is found in the left relation,
then the attributes of the left relation in the join result are filled
with null values.
A B
A B
⋈
Num Cube Square
2 8 4
3 18 9
5 75 –
Full Outer Join: ( A B)
In a full outer join, all tuples from both relations are included in
the result, irrespective of the matching condition.
A B
A B
⋈
Num Cube Square
2 4 8
3 9 18
4 16 –
5 – 75
Domain Relational Calculus (DRC)
• Domain Relational Calculus is a non-procedural query language equivalent in power
to Tuple Relational Calculus.
• Domain Relational Calculus provides only the description of the query but it does
not provide the methods to solve it.
• In Domain Relational Calculus, a query is expressed as,
• { < x1, x2, x3, ..., xn> | P (x1, x2, x3, ..., xn) }
• where, < x1, x2, x3, …, xn> represents resulting domains variables
• P (x1, x2, x3, …, xn) represents the condition or formula equivalent to the Predicate
calculus.
DRC
Let op denote an operator in the set {, =, ≤, ≥, 6=} and let X and Y
be domain variables. An atomic formula in DRC is one of the
following:
A formula is recursively defined to be one of the following, where p and q are
themselves formulas, and p(X) denotes a formula in which the variable X appears:
Examples of DRC Queries
(Q11) Find all sailors with a rating above 7
(Q1) Find the names of sailors who have reserved boat 103
DRC
(Q2) Find the names of sailors who have reserved a red boat.
INDEX
UNIT-4 PPT SLIDES
S.NO Module as per
Session planner
Lecture
No
PPT
Slide NO
------------------------------------------------------------------------------------------------------------------
1. The Form of a Basic SQL Queries
L1
2. Query operations & NESTED Queries
L2
3. NESTED Queries
L3
4. Aggregate Operators
L4
5. Null Values
L5
6. Complex I.C in SQL-92
L6
7. Triggers and Active Databases
L7
8. Designing Active Databases
L8
L1- 1 to L1- 15
L2- 1 to L2- 15
L3- 1 to L3- 9
L4- 1 to L4- 9
L5- 1 to L5 -9
L6- 1 to L6- 8
L7- 1 to L7- 5
L8- 1 to L8- 10
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Slide No:L3-1
Nested Queries
• A very powerful feature of SQL: a WHERE clause can
itself contain an SQL query! (Actually, so can FROM
and
HAVING clauses.)
• To find sailors who’ve not reserved #103, use NOT IN.
• To understand semantics of nested queries, think of a
nested loops evaluation: For each Sailors tuple,
check the qualification by computing the subquery.
Find names of sailors who’ve reserved boat #103:
SELECT S.sname
FROM Sailors S
WHERE S.sid IN (SELECT R.sid
FROM Reserves R
WHERE
R.bid=103)
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Overview of the SQL Query Language – Basic
Structure of SQL Queries, Set Operations,
Aggregate Functions – GROUPBY – HAVING,
Nested Sub queries, Views, Triggers, Procedures.
History
• IBM Sequel language developed as part of System R
project at the IBM San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92
features, plus varying feature sets from later standards
and special proprietary features.
– Not all examples here may work on your particular
system.
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
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.
Basic Query Structure
• A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
– Ai represents an attribute
– Ri represents a relation
– P is a predicate.
• This query is equivalent to the relational algebra
Create Table Construct
• An SQL relation is defined using the create table command:
Example:
create table branch (branch_name char(15), branch_city char(30),
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Basic Insertion and Deletion of Tuples
• Newly created table is empty
• Add a new tuple to account
insert into account values ('A-9732', 'Perryridge', 1200)
– Insertion fails if any integrity constraint is violated
• Delete all tuples from account
delete from account
Note: Will see later how to delete selected tuples
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Slide No:L2-4
Example of Conceptual Evaluation
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND
R.bid=103
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
(sid) sname rating age (sid) bid day
22 dustin 7 45.0 22 101 10/10/96
22 dustin 7 45.0 58 103 11/12/96
31 lubber 8 55.5 22 101 10/10/96
31 lubber 8 55.5 58 103 11/12/96
58 rusty 10 35.0 22 101 10/10/96
58 rusty 10 35.0 58 103 11/12/96
(Q15) Find the names and ages of all sailors.
SELECT DISTINCT S.sname, S.age FROM Sailors S
(Q11) Find all sailors with a rating above 7.
SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7
(Q16) Find the sids of sailors who have reserved a red boat.
SELECT R.sid FROM Boats B, Reserves R WHERE B.bid = R.bid AND B.color = ‘red‘
(Q2) Find the names of sailors who have reserved a red boat.
SELECT S.sname FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‘red‘
(Q3) Find the colors of boats reserved by Lubber.
SELECT B.color FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid =
B.bid AND S.sname = ‘Lubber‘
(Q4) Find the names of sailors who have reserved at least one boat.
SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid
Slide No:L2-12
Set Operations
• The set operations union, intersect, and except
operate on relations and correspond to the
relational algebra operations   
• Each of the above operations automatically
eliminates duplicates; to retain all duplicates use
the corresponding multiset versions union all,
intersect all and except all.
Set Operations
• Find all customers who have a loan, an account, or
both:
(select customer_name from depositor)
union
(select customer_name from borrower)
 Find all customers who have both a loan and an account.
(select customer_name from depositor)
intersect
(select customer_name from borrower)
 Find all customers who have an account but no loan.
(select customer_name from depositor)
except
(select customer_name from borrower)
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Find sid’s of sailors who’ve reserved a red or a green boat
• UNION: Can be used to
compute the union of any
two union-compatible sets of
tuples (which are themselves
the result of SQL queries).
• If we replace OR by AND in
the first version, what do we
get?
• Also available: EXCEPT
(What do we get if we replace
UNION by EXCEPT?)
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND (B.color=‘red’ OR B.color=‘green’)
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘red’
UNION SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘green’
Find sid’s of sailors who’ve reserved a red and a green boat
• INTERSECT: Can be used to
compute the intersection of
any two union-
compatible sets of tuples.
• Included in the SQL/92
standard, but some systems
don’t support it.
• Contrast symmetry of the
UNION and INTERSECT
queries with how much the
other versions differ.
SELECT S.sid
FROM Sailors S, Boats B1, Reserves R1,
Boats B2, Reserves R2
WHERE S.sid=R1.sid AND R1.bid=B1.bid
AND S.sid=R2.sid AND R2.bid=B2.bid
AND (B1.color=‘red’ AND B2.color=‘green’)
SELECT
S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘red’
INTERSECT SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘green’
Key field!
100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
Minus
 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.
 It has no duplicates and data arranged in ascending
order by default.
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
(Q2) Find the sids of all sailors who have reserved red boats but not green boats
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 S2.sid FROM Sailors S2, Reserves R2, Boats B2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color =
‗green‘.
NESTED QUERIES
A nested query is a query that has another query embedded within it.
the embedded query is called a subquery.
(Q1) Find the names of sailors who have reserved boat 103.
SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid
FROM Reserves R WHERE R.bid = 103 )
(Q2) Find the names of sailors who have reserved a red boat.
SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT
R.sid FROM Reserves R WHERE R.bid IN ( SELECT B.bid
FROM Boats B WHERE B.color =‘red‘ )
NESTED QUERIES
(Q3) Find the names of sailors who have not
reserved a red boat.
SELECT S.sname FROM Sailors S WHERE S.sid NOT IN ( SELECT
R.sid FROM Reserves R WHERE R.bid IN ( SELECT B.bid FROM
Boats B WHERE B.color = ‘red‘ ).
Correlated Nested Queries
the inner sub query has been completely independent
of the outer query:
(Q1) Find the names of sailors who have reserved boat number 103.
SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT *
FROM Reserves R WHERE R.bid = 103 AND R.sid = S.sid )
Set-Comparison Operators
(Q1) 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‘ )
(Q2) Find the sailors with the highest rating .
SELECT S.sid FROM Sailors S WHERE S.rating >=
ALL ( SELECT S2.rating FROM Sailors S2 )
More Examples of Nested Queries
(Q1) Find the names of sailors who have reserved both a red and a green boat.
SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE
S.sid = R.sid AND R.bid = B.bid AND B.color = ‗red‘ AND S.sid
IN ( SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color =
‗green‘)
AGGREGATE OPERATORS
 An aggregate function in SQL performs a calculation on multiple values
and returns a single value.
 SQL provides many aggregate functions that include avg, count, sum,
min, max, etc.
 An aggregate function ignores NULL values when it performs the
calculation, except for the count function.
.
1.COUNT ([DISTINCT] A): The number of (unique) values in the A column.
2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
4. MAX (A): The maximum value in the A column.
5. MIN (A): The minimum value in the A column.
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.
Examples
(Q1) Find the average age of all sailors.
SELECT AVG (S.age) FROM Sailors S
(Q2) Find the average age of sailors with a rating of 10.
SELECT AVG (S.age) FROM Sailors S WHERE S.rating = 10 SELECT S.sname, MAX
(S.age) FROMSailors S
Q3) Count the number of sailors.
SELECT COUNT (*) FROM Sailors S
GROUP BY
 The GROUP BY clause is a SQL command that is used
to group rows that have the same values.
 The GROUP BY clause is used in the SELECT statement.
 Optionally it is used in conjunction with aggregate
functions to produce summary reports from the database.
SQL GROUP BY Syntax
SELECT statements... GROUP BY column_name1[,column_name2,...] [HAVING
condition];
HERE
“SELECT statements…” is the standard SQL SELECT command query.
“GROUP BY column_name1” is the clause that performs the grouping based on
column_name1.
“[,column_name2,…]” is optional; represents other column names when the grouping is
done on more than one column.
“[HAVING condition]” is optional; it is used to restrict the rows affected by the GROUP
BY clause. It is similar to the WHERE clause.
GROUP BY
GROUP BY
GROUP BY and Having
Finding number students branch wise?
Finding the no of male and female students?
Finding the maximum percental from male and female students?
Finding average percentage of male students and
female students?
Finding the minimum percentile from male and female students?
Finding brances having only one students
Finding brances having more than one students
Finding branches in which students having minimum
percentage is greater than 70
Finding branches in which students having maximum
percentage is greater than 70
VIEWS
• In SQL, a view is a virtual table based on the
result-set of an SQL statement.
• A view contains rows and columns, just like a real
table.
• The fields in a view are fields from one or more real
tables in the database.
Syntax
• CREATE VIEW view_name AS SELECT
column1, column2..... FROM
table_name WHERE condition;
Student Details Student Marks
Creating View from a single table
• In this example we will create a View
named DetailsView from the table
StudentDetails.
Query:
• CREATE VIEW DetailsView AS SELECT NAME,
ADDRESS FROM StudentDetails WHERE S_ID
< 5;
SELECT * FROM DetailsView;
Creating View from multiple tables
• In this example we will create a View named
MarksView from two tables StudentDetails and
StudentMarks.
• To create a View from multiple tables we can
simply include multiple tables in the SELECT
statement. Query:
• CREATE VIEW MarksView AS SELECT
StudentDetails.NAME,
StudentDetails.ADDRESS,
StudentMarks.MARKS FROM
StudentDetails, StudentMarks WHERE
StudentDetails.NAME
= StudentMarks.NAME;
• SELECT * FROM MarksView;
DELETING VIEWS
• DROP VIEW view_name;
• DROP VIEW MarksView;
UPDATING VIEWS
If any one of these conditions is not met, then we will
not be allowed to update the view.
• The SELECT statement which is used to create the
view should not include GROUP BY clause or ORDER
BY clause.
• The SELECT statement should not have the
DISTINCT keyword.
• The View should have all NOT NULL values.
• The view should not be created using nested queries
or complex queries.
• The view should be created from a single table. If
the view is created using multiple tables then we
will not be allowed to update the view.
• We can use the CREATE OR REPLACE
VIEW statement to add or remove fields
from a view.
• Syntax:CREATE OR REPLACE VIEW
view_name AS SELECT column1,coulmn2,..
FROM table_name WHERE condition;
Inserting a row in a
view
• We can use the INSERT INTO statement of
SQL to insert a row in a View.
• Syntax:
• INSERT INTO view_name(column1,
column2 , column3,..) VALUES(value1,
value2, value3..);
• INSERT INTO DetailsView(NAME,
ADDRESS) VALUES("Suresh","Gurgaon");
Deleting a row from a
View
• DELETE FROM view_name WHERE
condition;
• DELETE FROM DetailsView
WHERE NAME="Suresh";
What is a Stored Procedure?
A procedure (often called a stored procedure) is a subroutine like a subprogram in
a regular computing language, stored in database.
• A procedure has a name, a parameter list, and SQL statement(s).
• An object created with CREATE PROCEDURE and invoked using the CALL
statement.
• A procedure does not have a return value but can modify its parameters for later
inspection by the caller. It can also generate result sets to be returned to the client
program.
CREATE PROCEDURE pr12 (IN SID int,OUT coint)
• begin
• select count(*) INTO co from emp where
ID=SID;
• END/
TRIGGERS
• The MySQL trigger is a database object that is associated with a table.
• It will be activated when a defined action is executed for the table.
• The trigger can be executed when you run one of the following MySQL
statements on the table: INSERT, UPDATE and DELETE and it can be
invoked before or after the event.
TRIGGERS
• A database trigger is procedural code that is
automatically executed in response to certain
events on a particular table or view in a
database.
• The trigger is mostly used for maintaining the
integrity of the information on the database.
CREATE TRIGGER trigger_name {BEFORE |
AFTER} {INSERT | UPDATE| DELETE } ON
table_name FOR EACH ROW trigger_body;
TRIGGERS
create trigger st1 before insert on account for
each row
• begin
• if new.acct_num<0 then
• signal SQLState '45000'
• SET MESSAGE_TEXT = 'acct number cant be negative';
• end if;
• end$

U-2.pptx igxitditdursruzyezrzmyayeTeYrsyrsurzursursursursursrusursruzruRuUeYeEuDuzurzurzruz

  • 1.
    Relational Algebra  RelationalAlgebra is procedural query language, which takes Relation as input and generate relation as output.  Relational algebra mainly provides theoretical foundation for relational databases and SQL.  It is used in the design of transactions and forms the conceptual basis for SQL  It consists of operators and manipulators which apply to relations and given relation as a result but do not change the actual relation in DB. The main purpose of using Relational Algebra is to define operators that transform one or more input relations into an output relation.
  • 5.
    Slide No:L6-6 Selection  rating 8 (S2)  sname,rating  rating  8 S ( ( 2)) 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile sid sname rating age 28 58 yuppy rusty 9 10 35.0 35.0 sname rating yuppy rusty 9 10
  • 7.
    Slide No:L6-5  sname,rating(S2) age 35.0 55.5  age(S2) Projection 100% freeSMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile sname rating yuppy 9 lubber 8 guppy 5 rusty 10
  • 15.
    Joins Join is acombination 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.
  • 20.
    Outer join: 1. LeftOuter Join 2. Right Outer Join 3. Full Outer Join
  • 21.
    OUTER JOINS • Inan outer join, along with tuples that satisfy the matching criteria, we also include some or all tuples that do not match the criteria. • Left Outer Join: • in the left outer join, operation allows keeping all tuple in the left relation. • However, if there is no matching tuple is found in right relation, then the attributes of right relation in the join result are filled with null values.
  • 22.
    Consider the following2 Tables A Num Square 2 4 3 9 4 16 B Num Cube 2 8 3 18 5 75 A B A B ⋈ Num Square Cube 2 4 8 3 9 18 4 16 – OUTER JOINS
  • 23.
    Right Outer Join:( A B ) • In the right outer join, operation allows keeping all tuple in the right relation. • However, if there is no matching tuple is found in the left relation, then the attributes of the left relation in the join result are filled with null values.
  • 24.
    A B A B ⋈ NumCube Square 2 8 4 3 18 9 5 75 –
  • 25.
    Full Outer Join:( A B) In a full outer join, all tuples from both relations are included in the result, irrespective of the matching condition. A B A B ⋈ Num Cube Square 2 4 8 3 9 18 4 16 – 5 – 75
  • 26.
    Domain Relational Calculus(DRC) • Domain Relational Calculus is a non-procedural query language equivalent in power to Tuple Relational Calculus. • Domain Relational Calculus provides only the description of the query but it does not provide the methods to solve it. • In Domain Relational Calculus, a query is expressed as, • { < x1, x2, x3, ..., xn> | P (x1, x2, x3, ..., xn) } • where, < x1, x2, x3, …, xn> represents resulting domains variables • P (x1, x2, x3, …, xn) represents the condition or formula equivalent to the Predicate calculus.
  • 27.
    DRC Let op denotean operator in the set {, =, ≤, ≥, 6=} and let X and Y be domain variables. An atomic formula in DRC is one of the following: A formula is recursively defined to be one of the following, where p and q are themselves formulas, and p(X) denotes a formula in which the variable X appears:
  • 28.
    Examples of DRCQueries (Q11) Find all sailors with a rating above 7 (Q1) Find the names of sailors who have reserved boat 103
  • 29.
    DRC (Q2) Find thenames of sailors who have reserved a red boat.
  • 30.
    INDEX UNIT-4 PPT SLIDES S.NOModule as per Session planner Lecture No PPT Slide NO ------------------------------------------------------------------------------------------------------------------ 1. The Form of a Basic SQL Queries L1 2. Query operations & NESTED Queries L2 3. NESTED Queries L3 4. Aggregate Operators L4 5. Null Values L5 6. Complex I.C in SQL-92 L6 7. Triggers and Active Databases L7 8. Designing Active Databases L8 L1- 1 to L1- 15 L2- 1 to L2- 15 L3- 1 to L3- 9 L4- 1 to L4- 9 L5- 1 to L5 -9 L6- 1 to L6- 8 L7- 1 to L7- 5 L8- 1 to L8- 10 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 31.
    Slide No:L3-1 Nested Queries •A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) • To find sailors who’ve not reserved #103, use NOT IN. • To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery. Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 32.
    Overview of theSQL Query Language – Basic Structure of SQL Queries, Set Operations, Aggregate Functions – GROUPBY – HAVING, Nested Sub queries, Views, Triggers, Procedures.
  • 33.
    History • IBM Sequellanguage developed as part of System R project at the IBM San Jose Research Laboratory • Renamed Structured Query Language (SQL) • ANSI and ISO standard SQL: – SQL-86 – SQL-89 – SQL-92 – SQL:1999 (language name became Y2K compliant!) – SQL:2003 • Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features. – Not all examples here may work on your particular system. 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 34.
    THE FORM OFA 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.
  • 35.
    Basic Query Structure •A typical SQL query has the form: select A1, A2, ..., An from r1, r2, ..., rm where P – Ai represents an attribute – Ri represents a relation – P is a predicate. • This query is equivalent to the relational algebra
  • 36.
    Create Table Construct •An SQL relation is defined using the create table command: Example: create table branch (branch_name char(15), branch_city char(30), 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 37.
    Basic Insertion andDeletion of Tuples • Newly created table is empty • Add a new tuple to account insert into account values ('A-9732', 'Perryridge', 1200) – Insertion fails if any integrity constraint is violated • Delete all tuples from account delete from account Note: Will see later how to delete selected tuples 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 38.
    Slide No:L2-4 Example ofConceptual Evaluation SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile (sid) sname rating age (sid) bid day 22 dustin 7 45.0 22 101 10/10/96 22 dustin 7 45.0 58 103 11/12/96 31 lubber 8 55.5 22 101 10/10/96 31 lubber 8 55.5 58 103 11/12/96 58 rusty 10 35.0 22 101 10/10/96 58 rusty 10 35.0 58 103 11/12/96
  • 41.
    (Q15) Find thenames and ages of all sailors. SELECT DISTINCT S.sname, S.age FROM Sailors S (Q11) Find all sailors with a rating above 7. SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7 (Q16) Find the sids of sailors who have reserved a red boat. SELECT R.sid FROM Boats B, Reserves R WHERE B.bid = R.bid AND B.color = ‘red‘
  • 42.
    (Q2) Find thenames of sailors who have reserved a red boat. SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‘red‘ (Q3) Find the colors of boats reserved by Lubber. SELECT B.color FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid AND S.sname = ‘Lubber‘ (Q4) Find the names of sailors who have reserved at least one boat. SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid
  • 43.
    Slide No:L2-12 Set Operations •The set operations union, intersect, and except operate on relations and correspond to the relational algebra operations    • Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multiset versions union all, intersect all and except all.
  • 44.
    Set Operations • Findall customers who have a loan, an account, or both: (select customer_name from depositor) union (select customer_name from borrower)  Find all customers who have both a loan and an account. (select customer_name from depositor) intersect (select customer_name from borrower)  Find all customers who have an account but no loan. (select customer_name from depositor) except (select customer_name from borrower) 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 45.
    Find sid’s ofsailors who’ve reserved a red or a green boat • UNION: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries). • If we replace OR by AND in the first version, what do we get? • Also available: EXCEPT (What do we get if we replace UNION by EXCEPT?) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’
  • 46.
    Find sid’s ofsailors who’ve reserved a red and a green boat • INTERSECT: Can be used to compute the intersection of any two union- compatible sets of tuples. • Included in the SQL/92 standard, but some systems don’t support it. • Contrast symmetry of the UNION and INTERSECT queries with how much the other versions differ. SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color=‘red’ AND B2.color=‘green’) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ Key field! 100% free SMS:- ON<space>UandiStar to 9870807070 for JNTU, Job Alerts, Tech News , GK News directly to ur Mobile
  • 47.
    Minus  It combinesthe 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.  It has no duplicates and data arranged in ascending order by default. Syntax: SELECT column_name FROM table1 MINUS SELECT column_name FROM table2;
  • 48.
    (Q2) Find thesids of all sailors who have reserved red boats but not green boats 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 S2.sid FROM Sailors S2, Reserves R2, Boats B2 WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = ‗green‘.
  • 49.
    NESTED QUERIES A nestedquery is a query that has another query embedded within it. the embedded query is called a subquery. (Q1) Find the names of sailors who have reserved boat 103. SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R WHERE R.bid = 103 ) (Q2) Find the names of sailors who have reserved a red boat. SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R WHERE R.bid IN ( SELECT B.bid FROM Boats B WHERE B.color =‘red‘ )
  • 50.
    NESTED QUERIES (Q3) Findthe names of sailors who have not reserved a red boat. SELECT S.sname FROM Sailors S WHERE S.sid NOT IN ( SELECT R.sid FROM Reserves R WHERE R.bid IN ( SELECT B.bid FROM Boats B WHERE B.color = ‘red‘ ).
  • 51.
    Correlated Nested Queries theinner sub query has been completely independent of the outer query: (Q1) Find the names of sailors who have reserved boat number 103. SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT * FROM Reserves R WHERE R.bid = 103 AND R.sid = S.sid ) Set-Comparison Operators (Q1) 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‘ )
  • 52.
    (Q2) Find thesailors with the highest rating . SELECT S.sid FROM Sailors S WHERE S.rating >= ALL ( SELECT S2.rating FROM Sailors S2 ) More Examples of Nested Queries (Q1) Find the names of sailors who have reserved both a red and a green boat. SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = ‗red‘ AND S.sid IN ( SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = ‗green‘)
  • 53.
    AGGREGATE OPERATORS  Anaggregate function in SQL performs a calculation on multiple values and returns a single value.  SQL provides many aggregate functions that include avg, count, sum, min, max, etc.  An aggregate function ignores NULL values when it performs the calculation, except for the count function. . 1.COUNT ([DISTINCT] A): The number of (unique) values in the A column. 2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column. 3. AVG ([DISTINCT] A): The average of all (unique) values in the A column. 4. MAX (A): The maximum value in the A column. 5. MIN (A): The minimum value in the A column.
  • 54.
    Now let usunderstand 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.
  • 55.
    Examples (Q1) Find theaverage age of all sailors. SELECT AVG (S.age) FROM Sailors S (Q2) Find the average age of sailors with a rating of 10. SELECT AVG (S.age) FROM Sailors S WHERE S.rating = 10 SELECT S.sname, MAX (S.age) FROMSailors S Q3) Count the number of sailors. SELECT COUNT (*) FROM Sailors S
  • 56.
    GROUP BY  TheGROUP BY clause is a SQL command that is used to group rows that have the same values.  The GROUP BY clause is used in the SELECT statement.  Optionally it is used in conjunction with aggregate functions to produce summary reports from the database. SQL GROUP BY Syntax SELECT statements... GROUP BY column_name1[,column_name2,...] [HAVING condition]; HERE “SELECT statements…” is the standard SQL SELECT command query. “GROUP BY column_name1” is the clause that performs the grouping based on column_name1. “[,column_name2,…]” is optional; represents other column names when the grouping is done on more than one column. “[HAVING condition]” is optional; it is used to restrict the rows affected by the GROUP BY clause. It is similar to the WHERE clause.
  • 57.
  • 58.
  • 59.
  • 60.
    Finding number studentsbranch wise? Finding the no of male and female students?
  • 61.
    Finding the maximumpercental from male and female students? Finding average percentage of male students and female students?
  • 62.
    Finding the minimumpercentile from male and female students?
  • 63.
    Finding brances havingonly one students Finding brances having more than one students
  • 64.
    Finding branches inwhich students having minimum percentage is greater than 70 Finding branches in which students having maximum percentage is greater than 70
  • 65.
    VIEWS • In SQL,a view is a virtual table based on the result-set of an SQL statement. • A view contains rows and columns, just like a real table. • The fields in a view are fields from one or more real tables in the database.
  • 66.
    Syntax • CREATE VIEWview_name AS SELECT column1, column2..... FROM table_name WHERE condition;
  • 67.
  • 68.
    Creating View froma single table • In this example we will create a View named DetailsView from the table StudentDetails. Query: • CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM StudentDetails WHERE S_ID < 5;
  • 69.
    SELECT * FROMDetailsView;
  • 70.
    Creating View frommultiple tables • In this example we will create a View named MarksView from two tables StudentDetails and StudentMarks. • To create a View from multiple tables we can simply include multiple tables in the SELECT statement. Query:
  • 71.
    • CREATE VIEWMarksView AS SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS FROM StudentDetails, StudentMarks WHERE StudentDetails.NAME = StudentMarks.NAME;
  • 72.
    • SELECT *FROM MarksView;
  • 73.
    DELETING VIEWS • DROPVIEW view_name; • DROP VIEW MarksView;
  • 74.
    UPDATING VIEWS If anyone of these conditions is not met, then we will not be allowed to update the view. • The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause. • The SELECT statement should not have the DISTINCT keyword. • The View should have all NOT NULL values. • The view should not be created using nested queries or complex queries. • The view should be created from a single table. If the view is created using multiple tables then we will not be allowed to update the view.
  • 75.
    • We canuse the CREATE OR REPLACE VIEW statement to add or remove fields from a view. • Syntax:CREATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,.. FROM table_name WHERE condition;
  • 76.
    Inserting a rowin a view • We can use the INSERT INTO statement of SQL to insert a row in a View. • Syntax: • INSERT INTO view_name(column1, column2 , column3,..) VALUES(value1, value2, value3..); • INSERT INTO DetailsView(NAME, ADDRESS) VALUES("Suresh","Gurgaon");
  • 77.
    Deleting a rowfrom a View • DELETE FROM view_name WHERE condition; • DELETE FROM DetailsView WHERE NAME="Suresh";
  • 78.
    What is aStored Procedure? A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular computing language, stored in database. • A procedure has a name, a parameter list, and SQL statement(s). • An object created with CREATE PROCEDURE and invoked using the CALL statement. • A procedure does not have a return value but can modify its parameters for later inspection by the caller. It can also generate result sets to be returned to the client program.
  • 79.
    CREATE PROCEDURE pr12(IN SID int,OUT coint) • begin • select count(*) INTO co from emp where ID=SID; • END/
  • 80.
    TRIGGERS • The MySQLtrigger is a database object that is associated with a table. • It will be activated when a defined action is executed for the table. • The trigger can be executed when you run one of the following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be invoked before or after the event.
  • 81.
    TRIGGERS • A databasetrigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. • The trigger is mostly used for maintaining the integrity of the information on the database.
  • 83.
    CREATE TRIGGER trigger_name{BEFORE | AFTER} {INSERT | UPDATE| DELETE } ON table_name FOR EACH ROW trigger_body;
  • 84.
    TRIGGERS create trigger st1before insert on account for each row • begin • if new.acct_num<0 then • signal SQLState '45000' • SET MESSAGE_TEXT = 'acct number cant be negative'; • end if; • end$