6 Lecture Notes Lendi DBMS - UNIT 2
6 Lecture Notes Lendi DBMS - UNIT 2
UNIT-II
Relational operations & Basic SQL: Relational Algebra, Relational Operations,
Relational Calculus, Tuple, And Domain Relational Calculus.
PL/ SQL: Database Languages, Data Types, Integrity Constraints, Simple And Nested
Queries, Implementation Of Different Types Of Joins, Stored Procedures
Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations
as input and yields instances of relations as output. It uses operators to perform queries. An
operator can be either unary or binary. They accept relations as their input and yield relations
as their output. Relational algebra is performed recursively on a relation and intermediate
results are also considered relations.
The fundamental operations of relational algebra are as follows −
Select
Project
Union
Set different
Cartesian product
Rename
Select Operation (σ)
It selects tuples that satisfy the given predicate from a relation.
Notation − σp(r)
Where σ stands for selection predicate and r stands for relation. p is a prepositional logic
formula that uses connectors like and, or, and not. These terms may use relational operators
like − =, ≠, ≥, <, >, ≤.
For example −
σsubject = "database"(Books)
Output − Selects tuples from books where the subject is 'database'.
σsubject = "database" and price = "450"(Books)
Output − Selects tuples from books where the subject is 'database' and 'price' is 450.
Project Operation (∏)
It projects column(s) that satisfy a given predicate.
Figure 4.9 S1 ∩ S2
Prepared by Dr. Satyanarayana. M, Professor, Dept. of CSE, LIET
DBMS UNIT-II
Figure 4.10 S1 − S2
The result of the cross-product S1 × R1 is shown in Figure 4.11 The fields in S1 × R1 have
the same domains as the corresponding fields in R1 and S1. In Figure 4.11 sid is listedin
parentheses to emphasize that it is not an inherited field name; only the corresponding
domain is inherited.
Figure 4.11 S1 × R1
RELATIONAL CALCULUS
Relational calculus is an alternative to relational algebra. In contrast to the algebra, which is
procedural, the calculus is nonprocedural, or declarative, in that it allows us to describe the
set of answers without being explicit about how they should be computed.
Types of Relational Calculus
A tuple variable is a variable that takes on tuples of a particular relation schema as values.
That
is, every value assigned to a given tuple variable has the same number and type of fields.
It is a non-procedural query language which is based on finding a number of tuple variables
also known as range variable for which predicate holds true. It describes the desired
information without giving a specific procedure for obtaining that information. The tuple
relational calculus is specified to select the tuples in a relation. In TRC, filtering variable uses
the tuples of a relation. The result of the relation can have one or more tuples.
Notation: A Query in the tuple relational calculus is expressed as following notation
{T | P (T)} or {T | Condition (T)}
Where T is the resulting tuples
P(T) is the condition used to fetch T.
For example: { T.name | Author(T) AND T.article = 'database' }
Output: This query selects the tuples from the AUTHOR relation. It returns a tuple with
'name' from Author who has written an article on 'database'.
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and
Universal Quantifiers (∀).
For example: { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}
Output: This query will yield the same result as the previous one.
3 DROP: Deletes an entire table, a view of a table or other objects in the database.
DML - Data Manipulation Language
Sr.No. Command & Description
Domain constraints
Referential integrity constraints
Key Constraints
There must be at least one minimal subset of attributes in the relation, which
can identify a tuple uniquely. This minimal subset of attributes is called key for
that relation. If there are more than one such minimal subsets, these are
called candidate keys.
Key constraints force that:
in a relation with a key attribute, no two tuples can have identical values
for key attributes.
a key attribute cannot have NULL values.
Key constraints are also referred to as Entity Constraints.
Domain Constraints
Attributes have specific values in real-world scenario. For example, age can only
be a positive integer. The same constraints have been tried to employ on the
attributes of a relation. Every attribute is bound to have a specific range of
values. For example, age cannot be less than zero and telephone numbers
cannot contain a digit outside 0-9.
Referential Integrity Constraints
Referential integrity constraints work on the concept of Foreign Keys. A foreign
key is a key attribute of a relation that can be referred in other relation.
Referential integrity constraint states that if a relation refers to a key attribute of
a different or same relation, then that key element must exist.
CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between
the constraint and the data action, the action is aborted by the constraint. It can be specified
when the table is created (using CREATE TABLE statement) or after the table is created
(using ALTER TABLE statement).
INTEGRITY CONSTRAINTS
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to
be accepted for storage in the table.
Syntax: CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example: CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax: CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example: CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax: CREATE TABLE Table_Name(column_name data_type(size)
CHECK(logical
expression), ….);
Example: CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or
combination of columns can be created as primary key, which can be used as a reference
from other tables. A table contains primary key is known as Master Table.
It must uniquely identify each record in a table.
It must contain unique values.
It cannot be a null field.
It cannot be multi port field.
It should contain a minimum no. of fields necessary to be called unique.
6. DEFAULT : The DEFAULT constraint is used to insert a default value into a column. The
default value will be added to all new records, if no other value is specified.
Syntax: CREATE TABLE Table_Name(col_name1,col_name2,col_name3
DEFAULT ‘<value>’);
Example: CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10),address
VARCHAR(20) DEFAULT ‘Visakhapatnam’);
THE FORM OF A BASIC SQL QUERY
This section presents the syntax of a simple SQL query and explains its meaning through a
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid=103
(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.
(Q5) Find the names of sailors who have reserved a red or a green boat.
(Q6) Find the names of sailors who have reserved a red and a green boat. It is tempting
to try to do this by simply replacing by in the denition of Tempboats:
(Q7) Find the names of sailors who have reserved at least two boats.
(Q8) Find the sids of sailors with age over 20 who have not reserved a red boat.
(Q9) Find the names of sailors who have reserved all boats. The use of the word all
(or every) is a good indication that the division operation might be applicable:
(Q10) Find the names of sailors who have reserved all boats called Interlake.
SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7
(Q12) Find the names and ages of sailors with a rating above 7.
(Q13) Find the sailor name, boat id, and reservation date for each reservation.
The answer to this query with and without the keyword DISTINCT on instance S3 of Sailors
is shown in Figures 5.4 and 5.5. The only difference is that the tuple for Horatio appears
twice if DISTINCT is omitted; this is because there are two sailors called Horatio and age 35.
(Q5) Compute increments for the ratings of persons who have sailed two different boats on
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‘ )
(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
In the nested queries that we have seen thus far, the inner subquery 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 FROMSailors 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‘)
Q9) 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 ))
AGGREGATE OPERATORS
We now consider a powerful class of constructs for computing aggregate values such as MIN
and SUM.
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.
(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
The GROUP BY and HAVING Clauses
we want to apply aggregate operations to each of a number of groups of rows in a relation,
where
the number of groups depends on the relation instance (i.e., is not known in advance). (Q31)
Find the age of the youngest sailor for each rating level.
SELECT MIN (S.age)
FROM Sailors S
WHERE S.rating = i
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Example Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
OUTPUT :
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Example Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and
the matched values from the left table. If there is no matching in both tables, it will return
NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
RIGHT JOIN table2 ON table1.matching_column = table2.matching_column;
Example Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Example Query
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
Procedures:
"A procedures or function is a group or set of SQL and PL/SQL statements that perform a
specific task."
A function and procedure is a named PL/SQL Block which is similar . The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value.
A procedure is a named PL/SQL block which performs one or more specific task. This is
similar to a procedure in other programming languages. A procedure has a header and a body.
The header consists of the name of the procedure and the parameters or variables passed to
the
procedure.
The body consists or declaration section, execution section and exception section similar to a
general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is
named
for repeated usage.
We can pass parameters to procedures in three ways :
Parameters Description
IN type
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Setting up multiple parameters is very easy. Just list each parameter and the data type
separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a
particular City with a particular PostalCode from the "Customers" table:
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
Execute the stored procedure above as follows: