DBMS Unit 2
DBMS Unit 2
1. Objective
To impart the knowledge of Relational model and integrity constraints over relation
and its implementation.
To impart the knowledge of Tuple Relational calculus.
To Impart the knowledge of views in SQL
To impart the knowledge of basic SQL query
To impart the knowledge of Nested Queries , Correlated Nested Queries
5. Evocation
6. Deliverables
Lecture -12
Relational Model concept: Relational model can represent as a table with columns and
rows. Each row is known as a tuple. Each table of the column has a name or attribute.
Domain: It contains a set of atomic values that an attribute can take.
Attribute: It contains the name of a column in a particular table. Each attribute Ai must
have a domain, dom (Ai)
Relational instance: In the relational database system, the relational instance is
represented by a finite set of tuples. Relation instances do not have duplicate tuples.
Relational schema: A relational schema contains the name of the relation and name of all
columns or attributes.
Relational key: In the relational key, each row has one or more attributes. It can identify
the row in the relation uniquely.
The Relational Algebra
• Relational Algebra is one of the two formal query languages associated with the
relational model.
• Relational algebra is a procedural query language. It gives a step by step process to
obtain the result of the query. It uses operators to perform queries.
• Relational algebra is a widely used procedural query language. It collects instances
of relations as input and gives occurrences of relations as output.
• It uses various operations to perform this action. Relational algebra operations are
performed recursively on a relation.
• The output of these operations is a new relation, which might be formed from one
or more input relations. Relational Algebra assumes that duplicate elimination is
always done, so that relations are always set of tuples.
Selection and Projection: Relational Algebra includes operators to select rows from a
relation andto project columns.
Selection:
This is used to fetch rows (tuples) from table (relation) which satisfies a given
condition.
Syntax: σ p(r)
Where, σ represents the Select Predicate, r is the name of relation (table
name in which you want to look for data), and p is the prepositional logic,
where we specify the conditions that must be satisfied by the data.
In prepositional logic, one can use unary and binary operators like =, <, >
etc, to specify the conditions.
Let's take an example of the Student table we specified above in the
Introduction of relational algebra, and fetch data for students with age
more than 17.
σ age > 17 (Student) This will fetch the tuples (rows) from table Student, for
which age will be greater than 17.
You can also use, and, or etc operators, to specify two conditions, for
example,σage > 17 and gender = 'Male' (Student)
This will return tuples (rows) from table Student with information of male
students, of age morethan 17.(Consider the Student table has an attribute
Gender too.)
Projection:
Project operation is used to project only a certain set of attributes of a
relation.
In simple words, If you want to see only the names all of the students in the
Student table, thenyou can use Project Operation.
It will only project or shows the columns or attributes asked for, and will
also remove duplicatedata from the columns.
Syntax: ∏A1, A2...(r)
Where A1, A2 etc are attribute names (column names).
For example,
∏Name, Age (Student)
Above statement will show us only the Name and Age columns for all the rows of
data inStudent table.
Renaming:
The results of relational algebra are also relations but without any name.
The rename operation provides database designers to rename the output
relation.
The rename-operation is denoted using small Greek letter rho (ρ).
It is written as: ρ x (E).
Example: We can use the rename operator to rename STUDENT relation to
STUDENT1. ρ(STUDENT1, STUDENT)
Lecture-13 Set operations Union:
For R 𝖴 S, The union of two relations R and S defines a relation that contains all the
tuples of R, or S, or both R and S, duplicate tuples being eliminated. R and S must be
union- compatible.
For a union operation to be applied, the following rules must hold −r and s must
have the same quantity of attributes.
Attribute domains must be compatible.
Duplicate tuples get automatically eliminated.
Syntax: A 𝖴 B where A and B are relations.
For example, if we have two tables RegularClass and ExtraClass, both have a
column student to save name of student, then,
∏Student(RegularClass) 𝖴 ∏Student(ExtraClass)
Above operation will give us name of Students who are attending both regular
classes and extra classes, eliminating repetition.
Intersection:
This operation is used to find data present in one relation and not present in the
second relation. This operation is also applicable on two relations, just like Union
operation.
The attribute name of A has to match with the attribute name in B.
The two-operand relations A and B should be either compatible or Union
compatible.
It should be defined relation consisting of the tuples that are in relation A, but not in
B. Syntax: A - B
Where A and B are relations.
For example, if we want to find name of students who attend the regular class but
not the extra class, then, we can use the below operation:
∏Student(RegularClass) - ∏Student(ExtraClass)
A
(Name Age Sex ) B
(Id Course)
Ram 14 M 1 DS
Sona 15 F 2 DBMS
kim 20 M
AXB
Name Age Sex Id Course
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
System Btech
Database Mtech
Database Btech
Algebra Btech
÷
Course
Btech
Mtech
=
Name
Database
The resulting operation must have all combinations of tuples of relation S that are present
in the first relation or R.
Lecture-14
Join Operations
Join operation is essentially a Cartesian product followed by a selection criterion. Join
operation denoted by ⋈. JOIN operation also allows joining variously related tuples from
different relations. A Join operation combines related tuples from different relations, if and
only if a given join condition is satisfied.
Types of JOIN:
Various forms of join operation are:
Inner Joins:
Conditional join
EQUI join
Natural join
Outer join:
Left Outer Join
Right Outer Join
Full Outer Join
Inner Join:
In an inner join, only those tuples that satisfy the matching criteria are included, while the
rest are excluded. Let's study various types of Inner Joins:
Conditional Join:
The general case of JOIN operation is called a Condition join. A pair of relation instances as
arguments and returns a relation instances.
Example
A ⋈c B=σc(AxB)
Theta join can use any conditions in the selection criteria.
For example:
A ⋈ A.column 2 > B.column 2 (B)
A ⋈A.column 2> B.column 2 (B)
column 1 column 2
1 2
EQUI join:
When a theta join uses only equivalence condition, it becomes a equi join.
For example:
A ⋈ A.column 2 = B.column 2 (B)
A ⋈ A.column 2 = B.column 2 (B)
column 1 column 2
1 1
EQUI join is the most difficult operations to implement efficiently in an RDBMS and one
reason why RDBMS have essential performance problems.
NATURAL JOIN (⋈)
Natural join can only be performed if there is a common attribute (column) between the
relations. The name and type of the attribute must be same.
Example
Consider the following two tables
C
Num Square
2 4
3 9
D
Num Cube
2 8
3 18
C⋈D
C ⋈ D
Num Square Cube
2 4 4
3 9 9
OUTER JOIN
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(A B)
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.
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
Lecture-15
Examples of Relational Algebra Queries:
Relational Calculus: Tuple Relational Calculus:
Relational Calculus is a non-procedural query language unlike relational algebra. Calculus
provides only the description of the query but it does not provide the methods to solve it.
Thus, it explains what to do but not how to do.
Relational Calculus exists in two forms:
Tuple Relational Calculus (TRC): variables take on tuples as values
Domain Relational Calculus (DRC): the variables range over field values
Tuple Relational Calculus (TRC):
A tuple variable is a variable that takes on tuples of a particular relation schema as values
i.e., every value assigned to a given tuple variable has the same number and type of fields.
In Tuple Calculus, a query is expressed as
{t| P(t)}
where t = resulting tuples,
P(t) = known as Predicate and these are the conditions that are used to fetch t
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.
P(t) may have various conditions logically combined with OR (∨), AND (𝖠), NOT(¬).
It also uses quantifiers:
∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t) is true.
∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r.
{T.name |T ∈ Student AND T.age > 17}
Example Queries
Say that we want to find the branch-name, loan-number, and amount for loans of over
$1200:
{t | t € loan 𝖠 t[amount] > 1200}
Suppose that we want only the loan-number attribute, rather than all attributes of the
loan relation. To write this query in the tuple relational calculus, we need to write an
expression for a relation on the schema (loan-number). We need those tuples on (loan-
number) such that there is a tuple in loan with the amount attribute > 1200. To express
this request, we need the construct “there exists” from mathematical logic.
The notation
€t € r (Q(t)) means “there exists a tuple t in relation r such that predicate Q(t) is true.”
Using this notation, we can write the query “Find the loan number for each loan of an
amount greater than $1200” as
{t | ∃s Є loan (t[loan-number] = s[loan-number] 𝖠 s[amount] > 1200)}
In English, we read the preceding expression as “The set of all tuples t such that there
exists a tuple s in relation loan for which the values of t and s for the loan-number
attribute are equal, and the value of s for the amount attribute is greater than$1200.”
Tuple variable t is defined on only the loan-number attribute, since that is the only
attribute havinga condition specified for t. Thus, the result is a relation on (loan number).
Consider the query “Find the names of all customers who have a loan from the Perryridge
branch.” This query is slightly more complex than the previous queries, since it involves
two relations: borrower and loan. As we shall see, however, all it requires is that we
have two “there exists” clauses in our tuple-relational-calculus expression, connected by
and (𝖠).We write the query as follows:
{t | ∃s Єborrower (t[customer-name] = s[customer-name]
𝖠 ∃ u Є loan (u[loan-number] = s[loan-number ]
𝖠 u[branch-name] = “Perryridge”))}
In English, this expression is “The set of all (customer-name) tuples for which the
customer has a loan that is at the Perryridge branch.” Tuple variable u ensures that the
customer is a borrower at the Perryridge branch. Tuple variable s is restricted to pertain
to the same loan number as s.
To find all customers who have a loan, an account, or both at the bank, we used the
union operation in the relational algebra. In the tuple relational calculus, we shall
need two “there exists” clauses,connected by or (∨):
{t | s Єborrower (t[customer-name] = s[customer-name])
∨ ∃ u Є depositor (t[customer-name] = u[customer-name])}
This expression gives us the set of all customer-name tuples for which at least one of the
followingholds:
The customer-name appears in some tuple of the borrower relation as a borrower
from the bank.
The customer-name appears in some tuple of the depositor relation as a depositor of
the bank.
If some customer has both a loan and an account at the bank, that customer appears only
once in the result, because the mathematical definition of a set does not allow duplicate
members.
If we now want only those customers who have both an account and a loan at the bank, all
we need to do is to change the or (∨) to and (𝖠) in the preceding expression.
{t | s Єborrower (t[customer-name] = s[customer-name])
𝖠 ∃ u Є depositor (t[customer-name] = u[customer-name])}
The result of this query appeared.
Now consider the query “Find all customers who have an account at the bank but do not
have a loanfrom the bank.” The tuple-relational-calculus expression for this query is
similar to the expressions that we have just seen, except for the use of the not
(¬) symbol:
{t | u Єdepositor (t[customer-name] = u[customer-name])
𝖠 ¬ s Є borrower (t[customer-name] = s[customer-name])}
Lecture-16
Integrity Constraints Over Relations:
Integrity constraints are a set of rules. It is used to maintain the quality of
information.
Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
Thus, integrity constraint is used to guard against accidental damage to the
database.
Super Key:
Super Key is defined as a set of attributes within a table that can uniquely identify each
record within a table. Super Key is a superset of Candidate key.
Ex: (student_id, name), now name of two students can be same, but their student_id can't
be same hence this combination can also be a key.
Candidate Key:
Candidate keys are defined as the minimal set of fields which can uniquely identify each
record in a table. It is an attribute or a set of attributes that can act as a Primary Key for a
table to uniquely identify each record in that table. There can be more than one candidate
key.In our example, student_id and phone both are candidate keys for table Student.
A candiate key can never be NULL or empty. And its value should be unique.
There can be more than one candidate keys for a table.
A candidate key can be a combination of more than one columns(attributes).
Composite Key
Key that consists of two or more attributes that uniquely identify any record in a table is
called Composite key. But the attributes which together form the Composite key are not
a key independentely or individually.
Ex: student_id and subject_id together will form the primary key, hence it is a composite
key.
SQL Key Constraints
Constraints enforce limits to the data or type of data that can be inserted/updated/deleted
from a table. The whole purpose of constraints is to maintain the data integrity during an
update/delete/insert into a table. In this tutorial we will learn several types of constraints
that can be created in RDBMS. SQL Constraints are rules used to limit the type of data that
can go into a table, to maintain the accuracy and integrity of the data inside table.
Constraints can be divided into the following two types,
Column level constraints: Limits only column data.
Table level constraints: Limits whole table data.
Constraints are used to make sure that the integrity of data is maintained in the database.
Following are the most used constraints that can be applied to a table.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NOT NULL Constraint
NOT NULL constraint restricts a column from having a NULL value. Once NOT NULL
constraint is applied to a column, you cannot pass a null value to that column. It enforces a
column to contain a proper value.
One important point to note about this constraint is that it cannot be defined at table level.
Example using NOT NULL constraint
CREATE TABLE Student(s_id int NOT NULL, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will not take NULL value.
UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE
constraint field will not have duplicate data. This constraint can be applied at column level
or table level.
Using UNIQUE constraint when creating a Table (Table Level)
Here we have a simple CREATE query to create a table, which will have a column s_id with
unique values.
CREATE TABLE Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will only have unique
values and wont take NULL value.
Customer_Detail Table
c_id Customer_Name address
101 Adam Noida
102 Alex Delhi
103 Stuart Rohtak
Order_Detail Table
Order_id Order_Name c_id
10 Order1 101
11 Order2 103
12 Order3 102
In Customer_Detail table, c_id is the primary key which is set as foreign key in Order_Detail
table. The value that is entered in c_id which is set as foreign key in Order_Detail table
must be present in Customer_Detail table where it is set as primary key. This prevents
invalid data to be inserted into c_id column of Order_Detail table.
If you try to insert any incorrect data, DBMS will return error and will not allow you to
insert the data.
Using FOREIGN KEY constraint at Table Level
CREATE table Order_Detail(order_id int PRIMARY KEY, order_name varchar(60) NOT
NULL,
c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id));
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id
column in Customer_Detail table.
On Delete Cascade : This will remove the record from child table, if that value of foriegn
key is deleted from the main table.
On Delete Null : This will set all the values in that record of child table as NULL, for which
the value of foriegn key is deleted from the main table.
If we don't use any of the above, then we cannot delete data from the main table for which
data in child table exists. We will get an error if we try to do so.
ERROR : Record in child table exist.
CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs
check on the values, before storing them into the database. Its like condition checking
before saving data into a column.
Lecture-17
Introduction to Views:
Views in SQL
Views in SQL are considered as a virtual table. A view also contains rows and columns. To
create the view, we can select the fields from one or more tables present in the database. A
view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE
condition;
2. Creating View from a single table
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM Student_Details WHERE
STU_ID < 4;
Just like table query, we can query the view to view the data.
SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
CREATE VIEW MarksView AS SELECT Student_Detail.NAME, Student_Detail.ADDRESS,
Student_Marks.MARKS FROM Student_Detail, Student_Mark WHERE
Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView:
Lecture -18
SQL Queries: Form of basic SQL Query
Structured Query Language, is a database computer language designed for
managing data in relational database management systems(RDBMS), and originally
based upon relational algebra and calculus. Its scope includes data insert, query,
update and delete, schema creation and modification, and data access control.
SQL command
• SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
• SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, and set permission for users.
c. ALTER: It is used to alter the structure of the database. This change could be either
tomodify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
ALTER TABLE MODIFY(COLUMN DEFINITION... );
EXAMPLE:
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax: TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,. column_nameN = valueN]
[WHERE CONDITION]
Example:
UPDATE students SET User_Name = 'Sonoo'WHERE Student_Id = '3'
DELETE: It is used to remove one or more row from a table.
Syntax:
DELETE FROM table_name [WHERE condition];
For example:
DELETE FROM javatpoint WHERE Author="Sonoo";
Lecture-19
Union:
• The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
• In the union operation, all the number of data type and columns must be same in
both the tableson which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its result set.
Syntax
SELECT column_name FROM table1UNION
SELECT column_name FROM table2;
Example: Find the ids of sailors who have reserved a red boat or a green boat.
SELECT R.sid FROM Boats B, Reserves R WHERE R.bid = B.bid AND B.color = ‘red’
UNION
SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid = B2.bid AND B2.color =
‘green’
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: Find the ids of sailors who have reserved a red boat or a green boat.
SELECT R.sid FROM Boats B, Reserves R WHERE R.bid = B.bid AND B.color = ‘red’
UNION ALL
SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid = B2.bid AND B2.color =
‘green’
Intersect:
• It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• 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: Find the ids of sailors who have reserved a red boat or a green boat.
SELECT R.sid FROM Boats B, Reserves R WHERE R.bid = B.bid AND B.color = ‘red’
INTERSECT
SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid = B2.bid AND B2.color =
‘green’
Minus: (except)
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. The keyword minus for
except
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
Example: : Find the ids of sailors who have reserved a red boat or a green boat.
SELECT R.sid FROM Boats B, Reserves R WHERE R.bid = B.bid AND B.color = ‘red’
MINUS
SELECT R2.sid FROM Boats B2, Reserves R2 WHERE R2.bid = B2.bid AND B2.color =
‘green’
Lecture:20
Nested Queries-
NESTED QUERIES
One of the most powerful features of SQL is nested queries. A nested query is a query
that has another query embedded within it; the embedded query is called a sub query.
The embedded query can of course be a nested query itself; thus queries that have very
deeply nested structures are possible. When writing a query, we sometimes need to
express a condition that refers to a table that must itself be computed. The query used
to compute this subsidiary table is a sub query and appears as part of the main query.
A sub query typically appears within the WHERE clause of a query. Sub queries can
sometimes appear in the FROM clause or the HAVING clause.
• In nested queries, a query is written inside a query. The result of inner query
is used inexecution of outer query.
• SQL also provides other set operations:
• In: to check if an element is in a given set
• Any and all: to compare a value with the elements in a given set, using comparison
operator
• Exists: to check if a set is empty
Independent Nested Queries: In independent nested queries, query execution starts
from innermost query to outermost queries. The execution of inner query is
independent of outer query, but the result of inner query is used in execution of outer
query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing independent
nested queries.
Ex: 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 RWHERE
R.bid = 103)
Correlated nested queries: In co-related nested queries, the output of inner query depends
on the row which is being currently executed in outer query. The inner query depends on the
row that is currentlybeing examined in the outer query.
Ex: Find the names of sailors who have reserved boat 103
SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT * FROM Reserves R
WHERER.bid =103 AND R.sid = S.sid )
Set comparison operators: IN and NOT IN are equivalent to = ANY and <> ALL, respectively.
EX: Find the name and the age of the youngest sailor.
SELECT S.sname, S.age FROM Sailors S
WHERE S.age <= ALL ( SELECT age FROM Sailors )
EX: Find the names and ratings of sailor whose rating is better than some sailor called Horatio.
SELECT S.sname, S.rating FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating FROM Sailors S2 WHERE S2.sname =
‘Horatio’ )
EX: Find the names of sailors who have reserved all boats.
SELECT S.sname FROM Sailors S
WHERE NOT EXISTS ( ( SELECT B.bid FROM Boats B) EXCEPT
( SELECT R.bid FROM Reserves R WHERE R.sid = S.sid ) )
Lecture-21
Aggregative Operators:
• SQL aggregation function is used to perform the calculations on multiple rows of a single
column of atable. It returns a single value.
• It is also used to summarize the dataAggregate Functions
Count, Sum, Avg, Max, Min
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 function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types. COUNT function uses the COUNT(*) that returns the count
of all the rows in a specified table. COUNT(*) considers duplicate and Null.
Count(*): Returns total number of records
Count(salary): Return number of Non Null values over the column salary.
Count(Distinct Salary): Return number of distinct Non Null values over the column salary .i.e 4
Ex: SELECT COUNT(*) FROM PRODUCT_MAST;
Sum():Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
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.
Ex: SELECT SUM(salary) FROM PRODUCT_MAST;
Avg(): The AVG function is used to calculate the average value of the numeric type. AVG function
returns theaverage of all non-Null values.
Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
Ex: SELECT avg(salary) FROM PRODUCT_MAST;
Min(): MIN function is used to find the minimum value of a certain column. This function
determines thesmallest value of all selected values of a column.
Min(salary): Minimum value in the salary column except NULL i.e., 40.
Ex: SELECT min(salary) FROM PRODUCT_MAST;
Max():MAX function is used to find the maximum value of a certain column. This function
determinesthe largest value of all selected values of a column.
Max(salary): Maximum value in the salary i.e., 80.
Ex: SELECT max(salary) FROM PRODUCT_MAST;
Lecture-22
FROM table_name
BY column_name
FROM Customers
GROUP BY Country;
Having:
• Only the groups that meet the HAVING criteria will be returned.
column-names
FROM table-name
WHERE condition
GROUP BY column-names
HAVING condition
table-name WHERE
ORDER BY column-names
Problem: List the number of customers in each country. Only include countries with
more than10 customers.
FROM Customer
COUNT(Id) > 10
Problem: List the number of customers in each country, except the USA, sorted high to low.
FROM Customer
COUNT(Id) >= 9
Lecture-23
OUTER JOIN
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(A B)
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.
Union
Select
Project
Relational Tuple Calculus
Intersection
SQL
Group By
Having Clause
DDL
DML
8. Sample Questions
Remember:
Apply:
1. Sailors(sid,sname,rating,age)
Boats(bid,bname,color)Reserves(sid,bid,day)
Find the names of sailors who have reserved a red or a green
boat
Find the names of sailors who have reserved a red and a but
not green boat.
2. Find all professors who taught at least two different
courses or two different sections of the same course in
the same classroom in the same semester and the same
year. Result contains both the faculty id, and the
semester/year information.
3. Find the equivalent view statement to this: SELECT
DISTINCT F.Name, C.CrsCode FROM FACULTY F, CLASS C
WHERE F.Id = C.InstructorId AND C.Year = 2002.
4. Find sailors whose rating is greater than that of every sailor called
Horatio
5. Find the age of the youngest sailor for each rating level
6. Find age of the youngest sailor with age 18, for each rating with at
least 2 such sailors
10. Mind Map
11. Student Summary
-------------------------