0% found this document useful (0 votes)
77 views79 pages

Relational Data Model and SQL Concepts

Uploaded by

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

Relational Data Model and SQL Concepts

Uploaded by

Arun Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Database Management Systems

Unit-2
Syllabus

Relational data Model and Language:

Relational Data Model Concepts, Integrity Constraints, Entity Integrity, Referential


Integrity, Keys Constraints, Domain Constraints, Relational Algebra, Relational
Calculus, Tuple and Domain Calculus. Introduction on SQL: Characteristics of SQL,
Advantage of SQL. SQl Data Type and Literals. Types of SQL Commands. SQL
Operators and Their Procedure. Tables, Views and Indexes. Queries and
Subqueries. Aggregate Functions. Insert, Update and Delete Operations, Joins,
Unions, Intersection, Minus, Cursors, Triggers, Procedures in SQL/PL SQL

2
Relational data Model
Relational Model (RM) represents the database as a collection of relations. A relation is
nothing but a table of values. Every row in the table represents a collection of related
data values. These rows in the table denote a real-world entity or relationship.
The table name and column names are helpful to interpret the meaning of values in each
row. The data are represented as a set of relations. In the relational model, data are
stored as tables. However, the physical storage of the data is independent of the way the
data are logically organized.
Some popular Relational Database management systems are:
● Oracle and RDB – Oracle
● SQL Server – Microsoft
● DB2 and Informix Dynamic Server – IBM
● MySQL-Oracle
● Postgres SQL

3
Relational Data Model Concept
● Tables − In relational data model, relations are saved in the format of Tables. This format
stores the relation among entities. A table has rows and columns, where rows represents
records and columns represent the attributes.
● Tuple − A single row of a table, which contains a single record for that relation is called a
tuple.
● Relation instance − A finite set of tuples in the relational database system represents
relation instance. Relation instances do not have duplicate tuples.
● Relation schema − A relation schema describes the relation name (table name), attributes,
and their names.
● Relation key − Each row has one or more attributes, known as relation key, which can
identify the row in the relation (table) uniquely.
● Attribute domain − Every attribute has some predefined value scope, known as attribute
domain.

4
Relational Data Model Concept

● A table is known as
Relation.
● A row is known as tuple.
● A value in a row is known
as field.
● All values in a tuple is
known as record.

5
Relational Integrity Constraints

Every relation has some conditions that must hold for it to be a valid relation.
These conditions are called Relational Integrity Constraints. There are three main
integrity constraints

There are many types of Integrity Constraints in DBMS. Constraints on the


Relational database management system is mostly divided into three main
categories are:

1. Domain Constraints
2. Key Constraints
3. Referential Integrity Constraints

6
Domain Constraint

Attributes have specific values in


ID NAME AGE
real-world scenario. For example, age
can only be a positive integer. The same
1001 Amit 25
constraints have been tried to employ
on the attributes of a relation. Every 3A5C Praveen -27
attribute is bound to have a specific
range of values. For example, age 1003 Swati 23
cannot be less than zero and telephone
numbers cannot contain a digit outside 1004 982263 25
0-9.

7
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 can not have NULL values.
Key constraints are also referred to as Entity Constraints.
**The null value is a special value that signifies that the value is
unknown or does not exist

8
Key Constraints

There are different kind of keys used in RDBMS


1. Super Key
2. Candidate Keys
3. Alternate keys
4. Primary Key
5. Foreign Key also known as reference key or referential integrity contraint

9
Super Key
A superkey is a set of one or more attributes
that, taken collectively, allow us to identify
uniquely a tuple in the relation.
For example, the ID attribute of the relation
instructor is sufficient to distinguish one
instructor tuple from another. Thus, ID is a
superkey.
The name attribute of instructor, on the other
hand, is not a superkey, because several
instructors might have the same name

10
Super Keys Examples

11
Candidate Key

The minimal set of attributes that can uniquely identify a tuple is known as a
candidate key.

12
Primary Key

A candidate key that is chosen by the database designer as the principal means of
identifying tuples within a relation is denoted as Primary key

13
Alternate Keys

Candidate keys other then primary key are called as alternate keys. For example: if
Student_ID is primary key then Student_SSN is an alternate key.

14
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.

I.e. Foreign Key can not be NULL.

15
Referential integrity Constraints

16
Schema
Diagram
for
University
Database

17
Schema of University Database

18
Relational Query Languages
A query language is a language in which a user requests information from the database. These languages are usually
on a level higher than that of a standard programming language.
Query languages can be categorized as
● imperative,
● functional
● declarative.

1. In an imperative query language, the user instructs the system to perform a specific sequence of operations on
the database to compute the desired result; such languages usually have a notion of state variables, which are
updated in the course of the computation.
2. In a functional query language, the computation is expressed as the evaluation of functions that may operate
on data in the database or on the results of other functions; functions are side-effect free, and they do not
update the program state.
3. In the declarative query language, the user describes the desired information without giving a specific
sequence of steps or function calls for obtaining that information; the desired information is typically described
using some form of mathematical logic. It is the job of the database system to figure out how to obtain the
desired information.

19
The Relational Algebra

The relational algebra consists of a set of operations that take one or two
relations as input and produce a new relation as their result.

Some of these operations, such as the select, project, and rename operations, are
called unary operations because they operate on one relation. The other
operations, such as union, Cartesian product, and set difference, operate on pairs
of relations and are, therefore, called binary operations.

Although the relational algebra operations form the basis for the widely used SQL
query language, database systems do not allow users to write queries in relational
algebra.

20
Relational Algebra
Unary Relational Operations
● SELECT (symbol: σ)
● PROJECT (symbol: π)
● RENAME (symbol: ρ)

Relational Algebra Operations From Set Theory


● UNION (υ)
● INTERSECTION ( ),
● DIFFERENCE (-)
● CARTESIAN PRODUCT ( x )

Binary Relational Operations


● JOIN
● DIVISION

21
Example: Select all tuples of the
Select Operation (σ) instructor relation we write:
σ (instrutor)
The select operation selects all those tuples that
satisfy a given predicate. We use the lowercase
Greek letter sigma (σ) to denote selection. The
predicate appears as a subscript to σ. The
argument relation is in parentheses after the σ.
σp(r)

σ is the predicate
r stands for relation which is the name of the
table
p is propositional logic

22
Select Operation

To select those tuples of the instructor relation where the instructor is in the
“Physics” department, we write:

OUTPUT:

23
Select Operation

Now find all instructors with salary greater than $90,000

We can use comparison operators =, ≠, <, ≤, >, and ≥ in the selection predicate. We
can also combine several predicates into a larger predicate by using the
connectives and (∧), or (∨), and not (¬).

Example: Find the instructors in Physics with a salary greater than $90,000,

24
Select Operation

The selection predicate may include


comparisons between two attributes. Consider
the relation department.

To find all departments whose name is the


same as their building name, we can write:

25
Exercise
● Find the employees who lives in city “Delhi”.

● Find the employees whose salary is greater than $100000.

● Find the employees who work for “National Bank”.

● Find the employees who works for “National Bank” and whose salary is greater than
$100000.

26
Exercise
● Find the employees who lives in city “Delhi”.
σ city = “Delhi” (employee)
● Find the employees whose salary is greater than $100000.
σ salary > “100000” (works)
● Find the employees who work for “National Bank”.
σ company_name = “National Bank” (works)
● Find the employees who works for “National Bank” and whose salary is greater than
$100000.
σ company_name = “National Bank” ⋀ salary > “100000” (works)

27
The Project Operation (Π)

The project operation allows us to produce this relation. The project operation is a
unary operation that returns its argument relation, with certain attributes left out.

Since a relation is a set, any duplicate rows are eliminated. Projection is denoted
by the uppercase Greek letter pi (Π). We list those attributes that we wish to
appear in the result as a subscript to Π. The argument relation follows in
parentheses. We write the query to produce such a list as:

28
The Project Operation (Π)

29
Composition of Relational Operations

Result of a relational operation is itself a relation


Example:
Find the names of all instructors in the Physics department.

30
Exercise

● Find the name of each branch located in “Delhi”.

● Find the ID of each borrower who has a loan.

● Find the account_number and branch_name having balance more than $100000

31
Exercise

● Find the name of each branch located in “Delhi”.

П branch_name ( σ branch_city = “ Delhi” (branch) )


● Find the ID of each borrower who has a loan.

П id (borrower)
● Find the account_number and branch_name having balance more than $100000

П account_number, branch_name ( σ balance > “100000” (account))

32
Exercise

● Find the name of employees who lives in city “Delhi”.

● Find the employee name and company name whose salary is greater than or equal
to $100000.

● Find the name of employee with there salary who work for “National Bank”.

● Find the name and street of employees whose city is “Chandigarh

33
Exercise
● Find the name of employees who lives in city “Delhi”.

П person_name ( σ city = “ Delhi” (employee) )


● Find the employee name and company name whose salary is greater than or equal to
$100000.

П person_name, company_name ( σ salary >= “ 100000” (works) )


● Find the name of employee with there salary who work for “National Bank”.

П person_name, salary ( σ company_name >= “ National Bank” (works) )


● Find the name and street of employees whose city is “Chandigarh

П person_name, street ( σ city >= “ Chandigarh” (employee) )


34
Cartesian Product
Since the same attribute name may appear in the schemas of both r1 and r2,
we need to devise a naming schema to distinguish between these attributes.
We do so here by attaching to an attribute the name of the relation from
which the attribute originally came. For example, the relation schema for

r = instructor × teaches is:

35
instructor teaches

36
instructor X teaches

37
Cartesian Product
Thus cartesian product create
surplus tuples which are not
required anymore thus cartesian
product is a lossy join.
To filter the required record from
available tuple, we can use select
operation with proper predicate.
Example

38
The Join Operation
The join operation allows us to combine a selection and a Cartesian product into a single
operation.
Consider relations r(R) and s(S), and let θ be a predicate on attributes in the schema R ∪ S. The
join operation r ⋈θ s is defined as follows:

Thus,
σ[Link] = [Link](instructor × teaches)
can equivalently be written as
instructor ⋈[Link] = [Link] teaches.

39
Example of Joins

1. Find all information about courses taught by instructors in the Physics


department:

2. The above query can also be written as

40
Queries

● Find the name of each employee who lives in “Delhi” and whose salary is
greater than $100000.

● Find the ID, name, and city of residence of each employee who works for
“NationalBank”.

41
Queries

● Find the name of each employee who lives in “Delhi” and whose salary is greater than $100000.

σ [Link] = “Delhi”

(employee ⋈employee.person_name = works.person_name works)

● Find the ID, name, and city of residence of each employee who works for “NationalBank”.

П[Link], employee.person_name, [Link]


(σ works.company_name = “NationalBank”
(employee ⋈emplpyee.person_name = works.person_name works))
42
Queries

● Find the ID, name, street address, and city of residence of each employee
who works for “NationalBank” and earns more than $10000.

● Find the name and salary of each employee whose resident city is same as
company city.

43
Queries

● Find the ID, name, street address, and city of residence of each employee
who works for “NationalBank” and earns more than $10000.

П[Link], employee.person_name, [Link](

σ works.company_name = “NationalBank” Λ [Link] >”100000”

(employee ⋈employee.person_name = works.person_name


works))

44
Queries

● Find the name and salary of each employee whose resident city is same as
company city.

Пemployee.person_name, [Link](
σ employee.person_name = works.person_name Λ [Link] = [Link]

(employee ⋈ works ⋈ company))

45
Schema of University Database

46
Queries

1. Find the ID and name of each instructor in the Physics department.


2. Find the ID and name of each instructor in a department located in the
building “Watson”.
3. Find the ID and name of each student who has taken at least one course in
the “Comp. Sci.” department.
4. Find the ID and name of each student who has taken at least one course
section in the year 2018.
5. Find the ID and name of each student who has not taken any course section
in the year 2018.

47
Solution

1. Find the ID and name of each instructor in the Physics department.

П[Link], [Link](
σ instructor.dept_name = “Physics” (instructor))

1. Find the ID and name of each instructor in a department located in the


building “Watson”.

П[Link], [Link](
σ [Link] = “Watson” (instructor ⋈ department))

48
Solution

3. Find the ID and name of each student who has taken at least one course in
the “Comp. Sci.” department.

П[Link], [Link](
σ [Link] = “Watson” (instructor ⋈ department))

3. Find the ID and name of each student who has taken at least one course
section in the year 2018.

49
Joins

The join operation allows us to combine a selection and a Cartesian product into a
single operation.

Consider relations r(R) and s(S), and let θ be a predicate on attributes in the
schema R U S. The join operation r ⋈θ s is defined as follows:

r ⋈θ s = σθ(r × s)

Thus, σ[Link] = [Link](instructor × teaches) can equivalently be written as

instructor ⋈[Link] = [Link] teaches.

50
Types of Joins

● Cartesian Join (Cross Product)( X )


● Natural Join (⋈ )
● Outer Join
○ LEFT Outer Join ( )
○ RIGHT Outer Join ( )
○ Full Outer Join ( )
● Theta Join (⋈θ)

51
Natural Join

The natural join is a binary operation that allows us to combine certain selections
and a Cartesian product into one operation. It is denoted by the join symbol ⋈.

The natural-join operation forms a Cartesian product of its two arguments,


performs a selection forcing equality on those attributes that appear in both
relation schemas, and finally removes duplicate attributes

52
Find the names of all instructors together with the course id of all courses they taught .

53
Find the names of all instructors in the Comp. Sci. department together with the course
titles of all the courses that the instructors teach.

54
Find the names of all instructors in the Comp. Sci. department together with the course
titles of all the courses that the instructors teach.

55
Outer Join

Natural Join and Cartesian join will eliminate the tuples, not satisfying the
condition or predicate.

Some time we need to preserve those eliminated tuple also for our need.

Outer join let you to combine the two relation without having loss of tuples.

56
The Union Operation
Find the set of all courses taught
in the Fall 2009 semester, the
Spring 2010 semester, or both.

First find the set of all courses taught in the Fall 2009 semester

Then find the set of all courses taught in the Spring 2010 semester.

Finally the result will be

57
Union Operation

The Union operation must perform on compatible relations only. Therefore, for a
union operation r ∪ s to be valid, we require that two conditions hold:

1. The relations r and s must be of the same arity. That is, they must have the
same number of attributes.
2. The domains of the ith attribute of r and the ith attribute of s must be the
same, for all i.

58
LEFT Outer Join A B

Num Square Num Cube


In the left outer join, operation allows
2 4 2 8
keeping all tuple in the left relation.
3 9 3 18
However, if there is no matching tuple
4 16 5 75
is found in right relation, then the
attributes of right relation in the join
A B
result are filled with null values.
Num Square Cube

2 4 8

3 9 18

4 16 NULL
59
RIGHT Outer Join A B

Num Square Num Cube


In the right outer join, operation
2 4 2 8
allows keeping all tuple in the right
3 9 3 18
relation. However, if there is no
matching tuple is found in the left 4 16 5 75
relation, then the attributes of the left
relation in the join result are filled A B
with null values. Num Square Cube

2 4 8

3 9 18

5 NULL 75
60
FULL Outer Join A B

Num Square Num Cube


In a full outer join, all tuples from both
2 4 2 8
relations are included in the result,
3 9 3 18
irrespective of the matching
condition. 4 16 5 75

A⋈B

Num Cube Square

2 4 8

3 9 18

4 16 NULL
61
5 NULL 75
Set Difference Operation

The set-difference operation, denoted by “−”, allows us to find tuples that are in
one relation but are not in another.

The expression r − s produces a relation containing those tuples in r but not in s.

Find all the courses taught in the Fall 2009 semester but not in Spring 2010
semester

As with the union operation, we must ensure that set differences are taken between compatible relations.
Therefore, for a set-difference operation r − s to be valid, we require that the relations r and s be of the
same arity, and that the domains of the ith attribute of r and the ith attribute of s be the same, for all i.

62
Intersection Operation

Find the set of all courses taught in both the Fall 2009 and the Spring 2010
semesters.

63
Division Operator

The division operator is used when we have to evaluate queries which contain the
keyword “ALL”.

Some instances where division operator is used are:

1. Which person has account in all the banks of a particular city?


2. Which students have taken all the courses required to graduate?

In above specified problem statements, the description after the keyword 'all'
defines a set which contains some elements and the final result contains those
units which satisfy these requirements.

64
Queries
● Find the names of all employees who work for “First Bank Corporation”.
● Find the names and cities of residence of all employees who work for “First Bank
Corporation”.
● Find the names, street addresses, and cities of residence of all employees who work for
“First Bank Corporation” and earn more than $10,000.
● Find the names of all employees in this database who live in the same city as the company
for which they work.
● Assume the companies may be located in several cities. Find all companies located in
every city in which “Small Bank Corporation” is located.
● Find the names of all employees who live in the same city and on the same street as do
their managers.
● Find the names of all employees in this database who do not work for “First Bank
Corporation”.
● Find the names of all employees who earn more than every employee of “Small Bank
Corporation” 65
Introduction to SQL

Structure Query Language(SQL) is a database query language used for storing and
managing data in Relational DBMS. SQL was the first commercial language
introduced for E.F Codd's Relational model of database.

Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use SQL as
the standard database query language. SQL is used to perform all types of data
operations in RDBMS.

66
SQL Command
Command Description
DDL: Data Definition Language
create to create new table or
This includes changes to the structure database
of the table like creation of table,
alter for alteration
altering table, deleting a table etc.

All DDL commands are auto-committed. truncate delete data from table
That means it saves all the changes
drop to drop a table
permanently in the database.
rename to rename a table

67
DML: Data Manipulation Language

DML commands are used for Command Description


manipulating the data stored in insert to insert a new row
the table and not the table itself.
update to update existing row
DML commands are not
delete to delete a row
auto-committed. It means
changes are not permanent to merge merging two rows or two
tables
database, they can be rolled back.

68
TCL: Transaction Control Language

These commands are to keep a


Command Description
check on other commands and
their affect on the database. commit to permanently save
These commands can annul
changes made by other rollback to undo change
commands by rolling the data
savepoint to save temporarily
back to its original state. It can
also make any temporary change
permanent.

69
DCL: Data Control Language

Data control language are the commands to Command Description


grant and take back authority from any grant grant permission of right
database user.
revoke take back permission.

DQL: Data Query Language


Data query language is used to
Command Description
fetch data from tables based on
select retrieve records from one or more table conditions that we can easily apply.

70
SQL Data Types
Datatype Use

INT used for columns which will store integer values.

FLOAT used for columns which will store float values.

DOUBLE used for columns which will store float values.

VARCHAR used for columns which will be used to store characters and integers, basically a string.

CHAR used for columns which will store char values(single character).

DATE used for columns which will store date values.

TEXT used for columns which will store text which is generally long in length. For example, if
you create a table for storing profile information of a social networking website, then for
about me section you can have a column of type TEXT.

71
SQL Command Description

SQL Command
CREATE DATABASE Creates a new database

CREATE TABLE Creates a new table

ALTER DATABASE Modifies a database

ALTER TABLE Modifies a table

DROP TABLE Deletes a table

CREATE INDEX Creates an index

DROP INDEX Deletes an index

SELECT Fetch data from database tables

UPDATE Modify data in a database table

DELETE Deletes data from a database table

INSERT INTO Inserts new data into a database table 74


SQL CREATE Commands

Create Database:

The SQL CREATE DATABASE Statement is used to create a new database.

Syntax: CREATE DATABASE database_name;

Example:

The following SQL statement creates a new database named as "my_database":

CREATE DATABASE my_database;

75
SQL CREATE Command
Create Table: Example
The SQL CREATE TABLE Statement is used to
create a new table in a database.
The following SQL statement creates a
Syntax: new table in the database named as
CREATE TABLE table_name "tbl_employee":
( CREATE TABLE tbl_employee
column_name1 datatype(size) [ NULL | NOT
NULL ], (
column_name2 datatype(size) [ NULL | NOT employee_id INT NOT NULL,
NULL ], last_name VARCHAR(100) NOT NULL,
column_name3 datatype(size) [ NULL | NOT
NULL ], first_name VARCHAR(100) NOT NULL,
.... address VARCHAR(255) NULL
); );

76
SQL: ALTER command

alter command is used for altering the table structure, such as,
● to add a column to existing table
● to rename any existing column
● to change datatype of any column or to modify its size.
● to drop a column from the table.
Using ALTER command we can add a column to any existing table. Following is
the
Syntax: Example:
ALTER TABLE table_name ADD ALTER TABLE student ADD
( (
column_name datatype address VARCHAR(200)
); );
77
ALTER Command: Modify an existing Column

ALTER command can also be used to modify data type of any existing column.
Following is the syntax,

ALTER TABLE table_name modify(


column_name datatype
);

Example:
ALTER TABLE student MODIFY(
address varchar(300));

78
ALTER Command: Rename a Column /Table
Using ALTER command you can rename an The syntax to rename a table in
existing column. Following is the syntax, MySQL is:
ALTER TABLE table_name
CHANGE COLUMN old_name new_name ALTER TABLE table_name
column_definition RENAME TO new_table_name;
[ FIRST | AFTER column_name ]

Example
Example:
ALTER TABLE contacts
ALTER TABLE contacts RENAME TO people;
CHANGE COLUMN contact_type ctype
varchar(20) NOT NULL;

79

You might also like