SlideShare a Scribd company logo
MODULE 2: Relational Model
SYLLABUS
• Structure of Relational Databases - Integrity
Constraints, Synthesizing ER diagram to
relational schema
• Introduction to Relational Algebra - select,
project, cartesian product operations, join - Equi-
join, natural join. query examples,
• Introduction to Structured Query Language
(SQL), Data Definition Language (DDL), Table
definitions and operations – CREATE, DROP,
ALTER, INSERT, DELETE, UPDATE.
Relational data model
• Represent database as a collection of relations
• Relation is a table which has values and rows in
table is a collection of related data values
• Row in relational table is called a tuple, column
header is attribute and table is a relation
EMP_NO Name Address Mobile number Age Salar
y
101 RAM XYZ 9898989898 20 10000
102 SAM CVF 9999999999 21 20000
103 SITA FDFD 888888888 22 30000
EMPLOYEE
Relation name
Attributes
Tuples
• In the relational model, all data is logically
structured within relations (also called table)
• Informally a relation may be viewed as a named
two-dimensional table representing an entity set.
• A relation has a fixed number of named columns
and variable number of rows.
Components of relational database
• The main components of relational database
structure are as follows:
1. Domains
2. Tuples (rows)
3. Columns
4. Keys
5. Relations (Tables)
Domain
• It has three parts
▫ Name
▫ Data type
▫ Format
• A Domain is a set of atomic values.
• Atomic means each value in the domain is
indivisible to the relational model.
• A domain has a logical definition:
e.g.“USA_phone_numbers” are the set of 10
digit phone numbers valid in the U.S.
• A domain may have a data-type or a format
defined for it. The USA_phone_numbers may
have a format: (ddd)-ddd-dddd where each d is a
decimal digit. E.g., Dates have various formats
such as month name, date, year or yyyy-mm-dd,
or dd mm,yyyy etc
Relation Model Database Pertemuan k.pptx
Tuples (rows)
• A tuple is an ordered set of values
• Tuple is a portion of a table containing data that
described only entity, relationship, or object
• Also known as record
• Each value is derived from an appropriate
domain.
• <Kumar, Singh, 52/57 store, 223001,
9889898989> is a tuple belonging to the
CUSTOMER relation.
Columns
• Columns in a table are also called attributes or
fields of the relation.
• A single cell in a table called field value, attribute
value or data element.
• For example, for the entity person, attributes
could include eye colour and height.
Key of a Relation
• Each row has a value of a data item (or set of
items) that uniquely identifies that row in the
table
 Called the key
• Sometimes row-ids or sequential numbers are
assigned as keys to identify the rows in a table
 Called artificial key or surrogate key
Relations (Tables)
• A relation may be thought of as a set of rows.
• A relation may alternately be thought of as a set
of columns.
• That is a table is perceived as a two-dimensional
structure composed of rows and columns.
• Each row represents a fact that corresponds to a
real-world entity or relationship.
• Each row has a value of an item or set of items
that uniquely identifies that row in the table
Schema of a Relation
• It is basically an outline of how data is organized
• It is denoted by R (A1, A2, .....An)
▫ Here R is relation name and
▫ it has some attributes A1 to An
• Each attribute have some domain and it is
represented by dom(Ai)
• Relation schema is used to describe a relation and
R is name of the relation
• Each attribute has a domain or a set of valid values.
▫ For example, the domain of Cust-id is 6 digit numbers.
Degree of a relation
• Degree of a relation is number of attributes in a
relation
• Eg
• STUDENT(Id, Name, Age, Departmentno)
▫ Has degree 4
• Using datatype of each the definition can be
written as
• STUDENT(Id:Integer, Name:String,Age:integer,
Departmentno:integer)
Relation State
• The relation state is a subset of the Cartesian
product of the domains of its attributes
▫ each domain contains the set of all possible values
the attribute can take.
• Example: attribute Cust-name is defined over
the domain of character strings of maximum
length 25
▫ dom(Cust-name) is varchar(25)
• The role these strings play in the CUSTOMER
relation is that of the name of a customer.
Relation Model Database Pertemuan k.pptx
• A relation state r(R) is a mathematical relation of
degree n on the domains dom(A1), dom(A2)…,
dom(An) which is a subset of Cartesian
product(X) of domains that define R
• Cartesian product specifies all possible
combination of values from underlying domains
Definition Summary
Informal Terms Formal Terms
Table Relation
Column Header Attribute
All possible Column
Values
Domain
Row Tuple
Table Definition Schema of a Relation
Populated Table State of the Relation
Relation Model Database Pertemuan k.pptx
Relational Integrity Constraints
• Constraints are conditions that must hold on all valid
relation states.
• There are three main types of constraints in the
relational model:
▫ Key constraints
▫ Entity integrity constraints
▫ Referential integrity constraints
• Another implicit constraint is the domain constraint
► Each attribute in a tuple is declared to be of a particular
domain (for example, integer, character, Boolean, String,
etc.) which specifies a constraint on the values that an
attribute can take.
► The entity integrity constraint states that primary key
value can't be null.
► This is because the primary key value is used to identify
individual rows in relation and if the primary key has a
null value, then we can't identify those rows.
► A table can contain a null value other than the primary
key field.
► Keys are the entity set that is used to identify an entity
within its entity set uniquely.
► An entity set can have multiple keys, but out of which one
key will be the primary key. A primary key can contain a
unique and not null value in the relational table.
► A referential integrity constraint is specified between two
tables.
► In the Referential integrity constraints, if a foreign key in Table 1 refers
to the Primary Key of Table 2, then every value of the Foreign Key in
Table 1 must be null or be available in Table 2.
Relational Database Schema
• Relational Database Schema:
▫ A set S of relation schemas that belong to the same
database.
▫ S is the name of the whole database schema
▫ S = {R1, R2, ..., Rn}
▫ R1, R2, …, Rn are the names of the individual
relation schemas within the database S
Relation Model Database Pertemuan k.pptx
Displaying a relational database schema
and its constraints
• Each relation schema can be displayed as a row of attribute
names
• The name of the relation is written above the attribute
names
• The primary key attribute (or attributes) will be underlined
• A foreign key (referential integrity) constraints is displayed
as a directed arc (arrow) from the foreign key attributes to
the referenced table
▫ Can also point the the primary key of the referenced relation
for clarity
• Next slide shows the COMPANY relational schema
diagram
Relation Model Database Pertemuan k.pptx
homework
• Consider the following relations for a database that keeps track of
student enrollment in courses and the books adopted for each
course:
• STUDENT(SSN, Name, Major, Bdate)
• COURSE(Course#, Cname, Dept)
• ENROLL(SSN, Course#, Quarter, Grade)
• BOOK_ADOPTION(Course#, Quarter, Book_ISBN)
• TEXT(Book_ISBN, Book_Title, Publisher, Author)
• Draw a relational schema diagram specifying the foreign keys
for this schema.
• 23.05.22 – 3rd
hr 2,4,15,17,27,30,32,57,62
Relation Model Database Pertemuan k.pptx
► An entity type within ER diagram is turned into a table.
► Each attribute turns into a column in the table.
► The key attribute of the entity is the primary key of the
table which is usually underlined.
► It is highly recommended that every table should start with
its primary key attribute conventionally named as
TablenameID.
► The initial relational schema is expressed in the following
format writing the table names with the attributes list
inside a parentheses as shown below for
PERSON( personid , name, dateOfBirth, gender)
PERSON
► personid is the primary key for the table : Person
personid name Dateofbirth gender
► If you have a multi-valued attribute, take the attribute and turn it into a new
entity or table of its own.
► Then make a 1:N relationship between the new entity and the existing one.
► Create a table for the attribute.
► Add the primary (id) column of the parent entity as a foreign key within
the new table
• PERSON( personid , name, dateOfBirth, gender)
• PERSON_PHONE(personid ,phone)
• personid within the table Person_Phone is a
foreign key referring to the personid of Person
• PERSON
• PERSON_PHONE
personid name dateOfBirth gender
personid phone
1:1
Relation Model Database Pertemuan k.pptx
Relation Model Database Pertemuan k.pptx
1:M
M:1
Relation Model Database Pertemuan k.pptx
BUILDING( Building_No,
Building_name, Address)
APARTMENT(Buiding_No,door_no,floor
)
Relation Model Database Pertemuan k.pptx
CAR(Car_ID,Serial_Number,Model_Number,Colo
r,Year,Customer_ID,Emp_ID)
CUSTOMER(Customer_ID,Name, PhoneNumber,
Address, Country, City)
EMPLOYEE(Emp_ID, Name, Address)
EMPLOYEE_QUALIFICATION(Emp_ID,Qualificatio
n)
INVOICE(Invoice_ID,Date,Emp_ID,Customer_ID
)
Relation Model Database Pertemuan k.pptx
EMPLOYEE(Emp_ID,
First_Name,Last_Name,DOB,Company_Id,Project_Id)
EMPLOYEE_CONTACT_NUMBER(Emp_ID,Contact_Number)
COMPANY(Company_Id,Company_Name,Location)
PROJECT(Project_Id,Project_Name,Start_Date)
SALARY(salary_Id,Date_Of_Salary,Mode_of_Payment)
• 24.05.22-4th
hr 2,4,13,15,17,34,41,57,
Types of keys:
• Keys
• Keys play an important role in the relational
database.
• It is used to uniquely identify any record or
row of data from the table. It is also used to
establish and identify relationships between
tables.
• Primary key
• It is the first key used to identify one
and only one instance of an entity
uniquely. An entity can contain
multiple keys, as we saw in the
PERSON table. The key which is most
suitable from those lists becomes a
primary key.
• In the EMPLOYEE table, ID can be the
primary key since it is unique for
each employee. In the EMPLOYEE
table, we can even select
License_Number and
Passport_Number as primary keys
since they are also unique.
• For each entity, the primary key
selection is based on requirements
and developers.
• Candidate key
• A candidate key is an
attribute or set of attributes
that can uniquely identify a
tuple.
• Except for the primary key,
the remaining attributes are
considered a candidate key.
The candidate keys are as
strong as the primary key.
• Super Key
• Super key is an attribute set
that can uniquely identify a
tuple.
• A super key is a superset of a
candidate key.
• Alternate key
• There may be one or more
attributes or a combination
of attributes that uniquely
identify each tuple in a
relation. These attributes or
combinations of the
attributes are called the
candidate keys. One key is
chosen as the primary key
from these candidate keys,
and the remaining candidate
key, if it exists, is termed the
alternate key.
• Composite key
• Whenever a primary key
consists of more than one
attribute, it is known as a
composite key. This key is
also known as Concatenated
Key.
Introduction to Structured Query
Language
SQL
• SQL provides
▫ A data definition language (DDL)
▫ A data manipulation language (DML)
▫ A data control language (DCL)
• In addition SQL
▫ Can be used from other languages
▫ Is often extended to provide common
programming constructs (such as if-then tests,
loops, variables, etc.)
Cont..
• SQL is a declarative (non-procedural) language
▫ Procedural - say exactly what the computer has
to do
▫ Non-procedural – describe the required result
(not the way to compute it)
• SQL is based on the relational model
▫ It has many of the same ideas
▫ Databases that support SQL are often
described as relational databases
▫ It is not always true to the model
Cont..
• E/R designs can be implemented in SQL
▫ Entities, attributes, and relationships can all
be expressed in terms of SQL
▫
Relations, Entities, Tables
Implementing E/R Designs
• Given an E/R design
▫ The entities become SQL tables
▫ Attributes of an entity become columns in the
corresponding table
▫ Relationships may be represented by foreign
keys
• Each entity becomes a
table in the database
▫ The name of the
table is often the
name of the entity
▫ The attributes
become columns of
the table with the
same name
Schema and Catalog Concepts in SQL
• An SQL schema is identified by a schema name,
and includes an authorization identifier to indicate
the user or account who owns the schema, as well as
descriptors for each element in the schema.
• Schema elements include tables, constraints, views,
domains, and other constructs that describe the
schema
• A schema is created via the CREATE SCHEMA
statement, which can include all the schema elements
definitions.
• Creates a schema called COMPANY, owned by
the user with authorization identifier ‘Jsmith’.
• not all users are authorized to create
schemas and schema elements.
• The privilege to create schemas, tables, and
other constructs must be explicitly granted to
the relevant user accounts by the system
administrator or DBA.
DATABASE LANGUAGES
1. Data Definition Language (DDL):
▫ It is used to specify a database conceptual schema using set
of
definitions.
▫ It supports the definition or declaration of database objects.
▫ The more common DDL commands are
 a.CREATE TABLE:
 ALTER TABLE
 DROP TABLE
 TRUNCATE
 COMMENT
 RENAME
2. Data Manipulation Language (DML)
▫ It provides a set of operations to support the basic data
manipulation operations on the data held in the database.
▫ It is used to query, update or retrieve data stored in a
database.
▫ Some of the tasks that come under DML are
 SELECT
 Used to query and display data from a database.
 INSERT
 Adds new rows to a table.
 UPDATE
 Changes an existing value in a column or group of columns
in a table.
 DELETE:
 Removes a specified row or set of rows from a table
Data Control Language
• DCL stands for Data Control Language.
▫ It is used to retrieve the stored or saved data.
▫ Grant: It is used to give user access privileges to a
database.
▫ Revoke: It is used to take back permissions from
the user.
Transaction Control Language
• TCL is used to run the changes made by the
DML statement.
▫ Commit: It is used to save the transaction on the
database.
▫ Rollback: It is used to restore the database to
original since the last Commit.
SQL Data Definition
• The set of relations in a database are specified using a
data-definition language (DDL)
• The SQL DDL allows specification of not only a set of
relations, but also information about each relation,
including:
▫ The schema for each relation.
▫ The types of values associated with each attribute.
▫ The integrity constraints.
▫ The set of indices to be maintained for each relation.
▫ The security and authorization information for each
relation.
▫ The physical storage structure of each relation on
disk.
Basic Schema Definition: CREATE
TABLE Command in SQL
• CREATE TABLE command is used to specify a
new relation by giving it a name and specifying
its attributes and initial constraints.
• The attributes are specified first, and each
attribute is given a name, a data type to specify
its domain of values, and any attribute
constraints, such as NOT NULL.
• The key, entity integrity, and referential integrity
constraints can be specified within the CREATE
TABLE statement
CREATION OF TABLES
• The SQL CREATE TABLE statement is used to
create a new table.
• Syntax
▫ CREATE TABLE table_name(
▫ column1 datatype,
▫ column2 datatype,
▫ column3 datatype, .....
▫ columnN datatype );
Attribute Data Types and Domains in
SQL
• The basic data types available for attributes
include
▫ numeric,
▫ char
▫ integer
▫ Boolean,
▫ date, and time
▫ Varchar
• CREATE TABLE CUSTOMERS
• ( ID INTEGER ,
• NAME VARCHAR (20),
• AGE INTEGER,
• ADDRESS CHAR (25) ,
• SALARY INTEGER);
• CREATE TABLE CUSTOMERS
• ( ID INTEGER NOT NULL,
• NAME VARCHAR (20) NOT NULL,
• AGE INT NOT NULL,
• ADDRESS CHAR (25) ,
• SALARY INTEGER);
Specifiying Key and Referiential
• PRIMARY KEY
▫ specifies one or more attributes that make up the
primary key of a relation.
▫ If a primary key has a single attribute, the clause
can follow the attribute directly
Primary Key Eg:
• CREATE TABLE STUDENT
• ( ROLL_NO INTEGER PRIMARY KEY,
• STU_NAME VARCHAR (35),
• STU_AGE INTEGER,
• STU_ADDRESS VARCHAR (20));
Primary Key Eg2:
• CREATE TABLE STUDENT
• ( ROLL_NO INTEGER NOT NULL,
• STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INTEGER NOT NULL,
• STU_ADDRESS VARCHAR (235),
• PRIMARY KEY (ROLL_NO) );
• UNIQUE
The UNIQUE constraint ensures that all values
in a column are different.
Both the UNIQUE and PRIMARY
KEY constraints provide a guarantee for
uniqueness for a column or set of columns
• CREATE TABLE Persons
(
Personid integer UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
DEFAULT constarint
• CREATE TABLE tablename ( Columnname
DEFAULT 'defaultvalue' );
• Eg:
▫ CREATE TABLE Geeks
▫ ( ID integer NOT NULL,
▫ Name varchar(255),
▫ Age integer,
▫ Location varchar(255) DEFAULT 'Noida');
▫ INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi');
INSERT INTO Geeks VALUES (5, 'Hema', 27); INSERT
INTO Geeks VALUES (6, 'Neha', 25, ‘Bihar'); INSERT
INTO Geeks VALUES (7, 'Khushi', 26);
FOREIGN KEY Constraint
• A FOREIGN KEY is a field (or collection of
fields) in one table, that refers to the
PRIMARY KEY in another table.
• The table with the foreign key is called the child
table, and the table with the primary key is called
the referenced or parent table.
• CREATE TABLE Persons
(
PersonID integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY(PersonID));
• CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Per
sons(PersonID)
);
Specifying Constraints on Tuples Using
CHECK
• CHECK clauses is specified at the end of a
CREATE TABLE statement
• These can be called tuple-based constraints
because they apply to each tuple individually
and are checked whenever a tuple is inserted or
modified
• The following SQL creates a CHECK constraint
on the "Age" column when the "Persons" table is
created. The CHECK constraint ensures that the
age of a person must be 18, or older:
ALTER TABLE
• The SQL ALTER TABLE command is used to add,
delete ,modify or rename columns in an existing table.
• The basic syntax of an ALTER TABLE command to add
a New Column in an existing table is as follows.
Eg:
• Existing
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY(Personid));
• ALTER TABLE Persons ADD( Age integer);
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
• ALTER TABLE table_name
ADD( column_name1 datatype1, column-name2
datatype2, column-name3 datatype3);
• The basic syntax of an ALTER TABLE command
to DROP COLUMN in an existing table is as
follows.
• The basic syntax of an ALTER TABLE command
to change the DATA TYPE of a column in a
table is as follows.
• ALTER TABLE Persons DROP COLUMN( Age );
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
• ALTER TABLE Persons MODIFY( Address
char(255 );
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
• ALTER TABLE Persons MODIFY( Address
varchar(300);
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(300),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
• ALTER TABLE Persons RENAME address TO location;
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
location varchar(300),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
DROP TABLE
• The SQL DROP TABLE statement is used to
remove a table definition and all the data,
indexes, triggers, constraints and permission
specifications for that table.
• You should be very careful while using this
command because once a table is deleted then
all the information available in that table will
also be lost forever.
• DROP TABLE Persons;
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Age integer,
PRIMARY KEY(Personid));
DML COMMANDS
INSERT Command
• INSERT is used to add a single tuple to a
relation.
• We must specify the relation name and a list of
values for the tuple.
• The values should be listed in the same order in
which the corresponding attributes were
specified in the CREATE TABLE command.
• INSERT INTO table_name (column1, column2,
column3, ...)
VALUES (value1, value2, value3, ...);
• INSERT INTO table_name
VALUES (value1, value2, value3, ...);
• CREATE TABLE Persons
( Personid integer,
LastName varchar(255) NOT
NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255));
• INSERT INTO Persons values
(1,’Nair’,’Rajiv’,’Heaven’,’Bang
lore’);
• INSERT INTO Persons
(Lname,City,Id,Fname,Addres
s) values (’Nair’,
’Banglore’,1,’Rajiv’,’Heaven’,);
• INSERT INTO Persons values
(1,’Nair’,’Rajiv’,’Heaven’,’Banglore’);
• INSERT INTO Persons
(Lname,City,Id,Fname,Address) values (’Nair’,
’Banglore’,1,’Rajiv’,’Heaven’,);
The DELETE Command
• The DELETE command removes tuples from a
relation.
• It includes a WHERE clause, to select the tuples to
be deleted.
• Tuples are explicitly deleted from only one table
at a time.
Relation Model Database Pertemuan k.pptx
• A missing WHERE clause specifies that all
tuples in the relation are to be deleted;
• the table remains in the database as an empty
table.
• DROP TABLE command is used to remove
the table definition
TRUNCATE TABLE COMMAND
• The SQL TRUNCATE TABLE command is used
to delete complete data from an existing table.
• You can also use DROP TABLE command to
delete complete table but it would remove
complete table structure form the database and
you would need to re-create this table once again
if you wish you store some data.
The UPDATE Command
• The UPDATE command is used to modify
attribute values of one or more selected tuples.
• WHERE clause in the UPDATE command
selects the tuples to be modified from a single
relation
PRE
SHARIKA
T
Relation Model Database Pertemuan k.pptx
THANK YOU
Introduction to Relational Algebra
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.
• Relational algebra is performed recursively on a
relation and intermediate results are also
considered as relations.
• These operations enable a user to specify basic retrieval
requests as relational algebra expressions.
• A sequence of relational algebra operations forms a
relational algebra expression, whose result will also be a
relation that represents the result of a database query
Types of Relational operation
• 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
The SELECT Operation
• The select operation selects tuples that satisfy a given
predicate.
• It is denoted by sigma (σ).
• Notation: σ p(r)
• Where:
▫ σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use
connectors like: AND OR and NOT. These relational can
use as relational operators like =, ≠, ≥, <, >, ≤.
LOAN Relation
BRANCH_NAME LOAN_NO AMOUNT
Downtown L-17 1000
Redwood L-23 2000
Perryride L-15 1500
Downtown L-14 1500
Mianus L-13 500
Roundhill L-11 900
Perryride L-16 1300
σ BRANCH_NAME="perryride" (LOAN)
BRANCH_NAME LOAN_NO AMOUNT
Perryride L-15 1500
Perryride L-16 1300
• Select the EMPLOYEE tuples whose department
is 4, or those whose salary is greater than
$30,000
• Clauses can be connected by the standard
Boolean operators and, or, and not to form a
general selection condition
• Select the tuples for all employees who either
work in department 4 and make over $25,000
per year, or work in department 5 and make over
$30,000,
Commutative Property of SELECT
• SELECT operation is commutative
• a sequence of SELECTs can be applied in any
order.
• we can always combine a cascade (or
sequence) of SELECT operations into a
single SELECT operation with a conjunctive
(AND) condition; that is,
Project Operation:
• This operation shows the list of those attributes
that we wish to appear in the result. Rest of the
attributes are eliminated from the table.
• It is denoted by ∏.
• Notation: ∏ A1, A2, An (r)
• Where
▫ A1, A2, A3 is used as an attribute name of
relation r.
CUSTOMER RELATION
NAME STREET CITY
Jones Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Johnson Alma Brooklyn
Brooks Senator Brooklyn
∏ NAME, CITY (CUSTOMER)
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Duplicate Elimination in PROJECT
• The PROJECT operation removes any duplicate
tuples, so the result of the PROJECT operation is
a set of distinct tuples, and hence a valid
relation.
• This is known as duplicate elimination.
Rename Operation:
• The rename operation is used to rename the
output relation. It is denoted by rho (ρ).
• Example: We can use the rename operator to
rename STUDENT relation to STUDENT1.
▫ ρ(STUDENT1, STUDENT)
RENAME Operation General form
• RENAME operation when applied to a relation R of
degree n is denoted by any of the following three
forms
• symbol ρ (rho) is used to denote the RENAME
operator,
• S is the new relation name, and
• B1, B2, ..., Bn are the new attribute names.
▫ The first expression renames both the relation and its
attributes,
▫ the second renames the relation only, and
▫ the third renames the attributes only.
• If the attributes of R are (A1, A2, ..., An) in that
order, then each Ai is renamed as Bi.
Example- In-Line relational algebra
expression
• retrieve the first name, last name, and salary of
all employees who work in department number
5, we must apply a SELECT and a PROJECT
operation
Example- Intermediate Relation
Union Operation:
• Suppose there are two tuples R and S. The union
operation contains all the tuples that are either in R
or S or both in R & S.
• It eliminates the duplicate tuples. It is denoted by .
∪
• Notation: R S
∪
• A union operation must hold the following
condition:
▫ R and S must have the attribute of the same number.
▫ Duplicate tuples are eliminated automatically.
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
∏ CUSTOMER_NAME (BORROW) ∏ CUSTOMER_NAME (DEPOSIT
∪
OR)
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
Set Intersection:
• Suppose there are two tuples R and S. The set
intersection operation contains all tuples that
are in both R & S.
• It is denoted by intersection .
∩
• Notation: R S
∩
∏ CUSTOMER_NAME (BORROW) ∏ CUSTOM
∩
ER_NAME (DEPOSITOR)
CUSTOMER_NAME
Smith
Jones
Set Difference:
• Suppose there are two tuples R and S. The set
intersection operation contains all tuples that
are in R but not in S.
• It is denoted by intersection minus (-).
• Notation: R - S
• The MINUS operation is not commutative; that
is, in general,
∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
Cartesian product (CROSS PRODUCT) OR
CROSS JOIN
• The Cartesian product is used to combine each
row in one table with each row in the other table.
It is also known as a cross product.
• It is denoted by X.
• Notation: E X D
• This is also a binary set operation, but the
relations on which it is applied do not have to be
union compatible
EMPLOYEE DEPARTMENT
EMP_ID EMP_NA
ME
EMP_DEP
T
1 Smith A
2 Harry C
3 John B
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
EMPLOYEE X DEPARTMENT
EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAM
E
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
Join Operations:
• A Join operation combines related tuples from
different relations, if and only if a given join
condition is satisfied.
• Outer Join:
• The outer join operation is an extension of the
join operation. It is used to deal with missing
information.
EMPLOYEE SALARY
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
EMP_CODE SALARY
101 50000
102 30000
103 25000
(EMPLOYEE SALARY)
⋈
EMP_CODE EMP_NAME SALARY
101 Stephan 50000
102 Jack 30000
103 Harry 25000
EMPLOYEE
FACT_WORKERS
EMP_NA
ME
STREET CITY
Ram Civil line Mumbai
Shyam Park
street
Kolkata
Ravi M.G.
Street
Delhi
Hari Nehru
nagar
Hyderaba
d
EMP_NA
ME
BRANCH SALARY
Ram Infosys 10000
Shyam Wipro 20000
Kuber HCL 30000
Hari TCS 50000
(EMPLOYEE FACT_WORKERS)
⋈
EMP_NAME STREET CITY BRANCH SALARY
Ram Civil line Mumbai Infosys 10000
Shyam Park street Kolkata Wipro 20000
Hari Nehru nagar Hyderabad TCS 50000
• An outer join is basically of three types:
• Left outer join
• Right outer join
• Full outer join
Left outer join:
• Left outer join contains the set of tuples of all
combinations in R and S that are equal on their
common attribute names.
• In the left outer join, tuples in R have no
matching tuples in S.
• It is denoted by .
⟕
EMPLOYEE FACT_WORKERS
⟕
EMP_NAME STREET CITY BRANCH SALARY
Ram Civil line Mumbai Infosys 10000
Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL
Right outer join:
• Right outer join contains the set of tuples of all
combinations in R and S that are equal on their
common attribute names.
• In right outer join, tuples in S have no matching
tuples in R.
• It is denoted by .
⟖
EMPLOYEE FACT_WORKERS
⟖
EMP_NAME BRANCH SALARY STREET CITY
Ram Infosys 10000 Civil line Mumbai
Shyam Wipro 20000 Park street Kolkata
Hari TCS 50000 Nehru street Hyderabad
Kuber HCL 30000 NULL NULL
Full outer join:
• Full outer join is like a left or right join except
that it contains all rows from both tables.
• In full outer join, tuples in R that have no
matching tuples in S and tuples in S that have no
matching tuples in R in their common attribute
name.
• It is denoted by .
⟗
EMPLOYEE FACT_WORKERS
⟗
EMP_NAME STREET CITY BRANCH SALARY
Ram Civil line Mumbai Infosys 10000
Shyam Park street Kolkata Wipro 20000
Hari Nehru street Hyderabad TCS 50000
Ravi M.G. Street Delhi NULL NULL
Kuber NULL NULL HCL 30000
Natural Join:
• A natural join is the set of tuples of all
combinations in R and S that are equal on their
common attribute names.
• It is denoted by .
⋈
EMPLOYEE SALARY
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
EMP_CODE SALARY
101 50000
102 30000
103 25000
∏EMP_NAME, SALARY (EMPLOYEE SALARY)
⋈
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
Equi join:
• It is also known as an inner join. It is the most
common join.
• It is based on matched data as per the equality
condition.
• The equi join uses the comparison operator(=).
• In the result of an EQUIJOIN we always have
one or more pairs of attributes that have
identical values in every tuple
student
ROLL_NO NAME ADDRESS PHONE AGE
1 RAM DELHI 9455123451 18
2 RAMESH GURGAON 9652431543 18
3 SUJIT ROHTAK 9156253131 20
4 SURESH DELHI 9156768971 18
employee
EMP_NO NAME ADDRESS PHONE AGE
1 RAM DELHI 9455123451 18
5 NARESH HISAR 9782918192 22
6 SWETA RANCHI 9852617621 21
4 SURESH DELHI 9156768971 18
Select students whose ROLL_NO is equal to
EMP_NO of employees
• STUDENT⋈STUDENT.ROLL_NO=EMPLOYEE.EMP_NOEM
PLOYEE
ROLL_NO NAME ADDRESS PHONE AGE
1 RAM DELHI 9455123451 18
4 SURESH DELHI 9156768971 18
PREPARED BY
SHARIKA T R,
SNGCE
Division Operation
• if you have two relations R and S, then, if U is a
relation defined as the cartesian product of
them: U = R x S. the division is the operator
such that: U ÷ R = S.
THANK YOU

More Related Content

PPTX
Module 2 2022 scheme BCS403 database management system
PPTX
The relational data model part[1]
PPTX
relational model.pptx
PDF
DBMS Unit-2.pdf
PPTX
Database relational model_unit3_2023 (1).pptx
PDF
Unit-2.pdf
PDF
Relational Model on Database management PPT
PPTX
DBMS: Week 04 - Relational Model in a Database
Module 2 2022 scheme BCS403 database management system
The relational data model part[1]
relational model.pptx
DBMS Unit-2.pdf
Database relational model_unit3_2023 (1).pptx
Unit-2.pdf
Relational Model on Database management PPT
DBMS: Week 04 - Relational Model in a Database

Similar to Relation Model Database Pertemuan k.pptx (20)

PDF
Advance database system(part 5)
PDF
Chapter 2 Database System Architecture.pdf
PDF
Databases - Unit 2.pdf
PPTX
Fundamentals of database system - Relational data model and relational datab...
PPTX
Relational model
PPT
1. UNIT - III.ppt
PPTX
ch04-The Relational Data Model and Relational Database Constraints [Compatibi...
DOCX
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
PDF
4_RelationalDataModelAndRelationalMapping.pdf
PDF
Chapter 2 Relational Data Model-part1
PPT
ER Digramms by Harshal wagh
PPTX
The Relational Model
PPTX
Relational Model
PPTX
Relational Model and Relational Algebra.pptx
PPTX
DBMS Module-2 notes for engineering BE vtu
PPTX
4-therelationaldatamodelandrelationaldatabaseconstraints-140128022150-phpapp0...
PPTX
Unit 2 new.pptx for the actual dbms chad
PPT
Chapter 5: Database superclass, subclass
PPTX
RELATIONALfsaaaaaaaaaaaakyagsgs MODEL.pptx
PDF
Relational Database Model Database Management system
Advance database system(part 5)
Chapter 2 Database System Architecture.pdf
Databases - Unit 2.pdf
Fundamentals of database system - Relational data model and relational datab...
Relational model
1. UNIT - III.ppt
ch04-The Relational Data Model and Relational Database Constraints [Compatibi...
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
4_RelationalDataModelAndRelationalMapping.pdf
Chapter 2 Relational Data Model-part1
ER Digramms by Harshal wagh
The Relational Model
Relational Model
Relational Model and Relational Algebra.pptx
DBMS Module-2 notes for engineering BE vtu
4-therelationaldatamodelandrelationaldatabaseconstraints-140128022150-phpapp0...
Unit 2 new.pptx for the actual dbms chad
Chapter 5: Database superclass, subclass
RELATIONALfsaaaaaaaaaaaakyagsgs MODEL.pptx
Relational Database Model Database Management system
Ad

Recently uploaded (20)

PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Business Ethics Teaching Materials for college
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Insiders guide to clinical Medicine.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Institutional Correction lecture only . . .
PPTX
Cell Types and Its function , kingdom of life
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
2.FourierTransform-ShortQuestionswithAnswers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPH.pptx obstetrics and gynecology in nursing
Business Ethics Teaching Materials for college
102 student loan defaulters named and shamed – Is someone you know on the list?
Insiders guide to clinical Medicine.pdf
Complications of Minimal Access Surgery at WLH
Institutional Correction lecture only . . .
Cell Types and Its function , kingdom of life
Week 4 Term 3 Study Techniques revisited.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Ad

Relation Model Database Pertemuan k.pptx

  • 2. SYLLABUS • Structure of Relational Databases - Integrity Constraints, Synthesizing ER diagram to relational schema • Introduction to Relational Algebra - select, project, cartesian product operations, join - Equi- join, natural join. query examples, • Introduction to Structured Query Language (SQL), Data Definition Language (DDL), Table definitions and operations – CREATE, DROP, ALTER, INSERT, DELETE, UPDATE.
  • 3. Relational data model • Represent database as a collection of relations • Relation is a table which has values and rows in table is a collection of related data values • Row in relational table is called a tuple, column header is attribute and table is a relation
  • 4. EMP_NO Name Address Mobile number Age Salar y 101 RAM XYZ 9898989898 20 10000 102 SAM CVF 9999999999 21 20000 103 SITA FDFD 888888888 22 30000 EMPLOYEE Relation name Attributes Tuples
  • 5. • In the relational model, all data is logically structured within relations (also called table) • Informally a relation may be viewed as a named two-dimensional table representing an entity set. • A relation has a fixed number of named columns and variable number of rows.
  • 6. Components of relational database • The main components of relational database structure are as follows: 1. Domains 2. Tuples (rows) 3. Columns 4. Keys 5. Relations (Tables)
  • 7. Domain • It has three parts ▫ Name ▫ Data type ▫ Format • A Domain is a set of atomic values. • Atomic means each value in the domain is indivisible to the relational model.
  • 8. • A domain has a logical definition: e.g.“USA_phone_numbers” are the set of 10 digit phone numbers valid in the U.S. • A domain may have a data-type or a format defined for it. The USA_phone_numbers may have a format: (ddd)-ddd-dddd where each d is a decimal digit. E.g., Dates have various formats such as month name, date, year or yyyy-mm-dd, or dd mm,yyyy etc
  • 10. Tuples (rows) • A tuple is an ordered set of values • Tuple is a portion of a table containing data that described only entity, relationship, or object • Also known as record • Each value is derived from an appropriate domain.
  • 11. • <Kumar, Singh, 52/57 store, 223001, 9889898989> is a tuple belonging to the CUSTOMER relation.
  • 12. Columns • Columns in a table are also called attributes or fields of the relation. • A single cell in a table called field value, attribute value or data element. • For example, for the entity person, attributes could include eye colour and height.
  • 13. Key of a Relation • Each row has a value of a data item (or set of items) that uniquely identifies that row in the table  Called the key • Sometimes row-ids or sequential numbers are assigned as keys to identify the rows in a table  Called artificial key or surrogate key
  • 14. Relations (Tables) • A relation may be thought of as a set of rows. • A relation may alternately be thought of as a set of columns. • That is a table is perceived as a two-dimensional structure composed of rows and columns. • Each row represents a fact that corresponds to a real-world entity or relationship. • Each row has a value of an item or set of items that uniquely identifies that row in the table
  • 15. Schema of a Relation • It is basically an outline of how data is organized • It is denoted by R (A1, A2, .....An) ▫ Here R is relation name and ▫ it has some attributes A1 to An • Each attribute have some domain and it is represented by dom(Ai) • Relation schema is used to describe a relation and R is name of the relation • Each attribute has a domain or a set of valid values. ▫ For example, the domain of Cust-id is 6 digit numbers.
  • 16. Degree of a relation • Degree of a relation is number of attributes in a relation • Eg • STUDENT(Id, Name, Age, Departmentno) ▫ Has degree 4 • Using datatype of each the definition can be written as • STUDENT(Id:Integer, Name:String,Age:integer, Departmentno:integer)
  • 17. Relation State • The relation state is a subset of the Cartesian product of the domains of its attributes ▫ each domain contains the set of all possible values the attribute can take. • Example: attribute Cust-name is defined over the domain of character strings of maximum length 25 ▫ dom(Cust-name) is varchar(25) • The role these strings play in the CUSTOMER relation is that of the name of a customer.
  • 19. • A relation state r(R) is a mathematical relation of degree n on the domains dom(A1), dom(A2)…, dom(An) which is a subset of Cartesian product(X) of domains that define R • Cartesian product specifies all possible combination of values from underlying domains
  • 20. Definition Summary Informal Terms Formal Terms Table Relation Column Header Attribute All possible Column Values Domain Row Tuple Table Definition Schema of a Relation Populated Table State of the Relation
  • 22. Relational Integrity Constraints • Constraints are conditions that must hold on all valid relation states. • There are three main types of constraints in the relational model: ▫ Key constraints ▫ Entity integrity constraints ▫ Referential integrity constraints • Another implicit constraint is the domain constraint
  • 23. ► Each attribute in a tuple is declared to be of a particular domain (for example, integer, character, Boolean, String, etc.) which specifies a constraint on the values that an attribute can take.
  • 24. ► The entity integrity constraint states that primary key value can't be null. ► This is because the primary key value is used to identify individual rows in relation and if the primary key has a null value, then we can't identify those rows. ► A table can contain a null value other than the primary key field.
  • 25. ► Keys are the entity set that is used to identify an entity within its entity set uniquely. ► An entity set can have multiple keys, but out of which one key will be the primary key. A primary key can contain a unique and not null value in the relational table.
  • 26. ► A referential integrity constraint is specified between two tables. ► In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be available in Table 2.
  • 27. Relational Database Schema • Relational Database Schema: ▫ A set S of relation schemas that belong to the same database. ▫ S is the name of the whole database schema ▫ S = {R1, R2, ..., Rn} ▫ R1, R2, …, Rn are the names of the individual relation schemas within the database S
  • 29. Displaying a relational database schema and its constraints • Each relation schema can be displayed as a row of attribute names • The name of the relation is written above the attribute names • The primary key attribute (or attributes) will be underlined • A foreign key (referential integrity) constraints is displayed as a directed arc (arrow) from the foreign key attributes to the referenced table ▫ Can also point the the primary key of the referenced relation for clarity • Next slide shows the COMPANY relational schema diagram
  • 31. homework • Consider the following relations for a database that keeps track of student enrollment in courses and the books adopted for each course: • STUDENT(SSN, Name, Major, Bdate) • COURSE(Course#, Cname, Dept) • ENROLL(SSN, Course#, Quarter, Grade) • BOOK_ADOPTION(Course#, Quarter, Book_ISBN) • TEXT(Book_ISBN, Book_Title, Publisher, Author) • Draw a relational schema diagram specifying the foreign keys for this schema.
  • 32. • 23.05.22 – 3rd hr 2,4,15,17,27,30,32,57,62
  • 34. ► An entity type within ER diagram is turned into a table. ► Each attribute turns into a column in the table. ► The key attribute of the entity is the primary key of the table which is usually underlined. ► It is highly recommended that every table should start with its primary key attribute conventionally named as TablenameID.
  • 35. ► The initial relational schema is expressed in the following format writing the table names with the attributes list inside a parentheses as shown below for PERSON( personid , name, dateOfBirth, gender) PERSON ► personid is the primary key for the table : Person personid name Dateofbirth gender
  • 36. ► If you have a multi-valued attribute, take the attribute and turn it into a new entity or table of its own. ► Then make a 1:N relationship between the new entity and the existing one. ► Create a table for the attribute. ► Add the primary (id) column of the parent entity as a foreign key within the new table
  • 37. • PERSON( personid , name, dateOfBirth, gender) • PERSON_PHONE(personid ,phone) • personid within the table Person_Phone is a foreign key referring to the personid of Person • PERSON • PERSON_PHONE personid name dateOfBirth gender personid phone
  • 38. 1:1
  • 41. 1:M
  • 42. M:1
  • 46. CAR(Car_ID,Serial_Number,Model_Number,Colo r,Year,Customer_ID,Emp_ID) CUSTOMER(Customer_ID,Name, PhoneNumber, Address, Country, City) EMPLOYEE(Emp_ID, Name, Address) EMPLOYEE_QUALIFICATION(Emp_ID,Qualificatio n) INVOICE(Invoice_ID,Date,Emp_ID,Customer_ID )
  • 51. • Keys • Keys play an important role in the relational database. • It is used to uniquely identify any record or row of data from the table. It is also used to establish and identify relationships between tables.
  • 52. • Primary key • It is the first key used to identify one and only one instance of an entity uniquely. An entity can contain multiple keys, as we saw in the PERSON table. The key which is most suitable from those lists becomes a primary key. • In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the EMPLOYEE table, we can even select License_Number and Passport_Number as primary keys since they are also unique. • For each entity, the primary key selection is based on requirements and developers.
  • 53. • Candidate key • A candidate key is an attribute or set of attributes that can uniquely identify a tuple. • Except for the primary key, the remaining attributes are considered a candidate key. The candidate keys are as strong as the primary key.
  • 54. • Super Key • Super key is an attribute set that can uniquely identify a tuple. • A super key is a superset of a candidate key.
  • 55. • Alternate key • There may be one or more attributes or a combination of attributes that uniquely identify each tuple in a relation. These attributes or combinations of the attributes are called the candidate keys. One key is chosen as the primary key from these candidate keys, and the remaining candidate key, if it exists, is termed the alternate key.
  • 56. • Composite key • Whenever a primary key consists of more than one attribute, it is known as a composite key. This key is also known as Concatenated Key.
  • 57. Introduction to Structured Query Language
  • 58. SQL • SQL provides ▫ A data definition language (DDL) ▫ A data manipulation language (DML) ▫ A data control language (DCL) • In addition SQL ▫ Can be used from other languages ▫ Is often extended to provide common programming constructs (such as if-then tests, loops, variables, etc.)
  • 59. Cont.. • SQL is a declarative (non-procedural) language ▫ Procedural - say exactly what the computer has to do ▫ Non-procedural – describe the required result (not the way to compute it) • SQL is based on the relational model ▫ It has many of the same ideas ▫ Databases that support SQL are often described as relational databases ▫ It is not always true to the model
  • 60. Cont.. • E/R designs can be implemented in SQL ▫ Entities, attributes, and relationships can all be expressed in terms of SQL ▫
  • 62. Implementing E/R Designs • Given an E/R design ▫ The entities become SQL tables ▫ Attributes of an entity become columns in the corresponding table ▫ Relationships may be represented by foreign keys
  • 63. • Each entity becomes a table in the database ▫ The name of the table is often the name of the entity ▫ The attributes become columns of the table with the same name
  • 64. Schema and Catalog Concepts in SQL • An SQL schema is identified by a schema name, and includes an authorization identifier to indicate the user or account who owns the schema, as well as descriptors for each element in the schema. • Schema elements include tables, constraints, views, domains, and other constructs that describe the schema • A schema is created via the CREATE SCHEMA statement, which can include all the schema elements definitions.
  • 65. • Creates a schema called COMPANY, owned by the user with authorization identifier ‘Jsmith’. • not all users are authorized to create schemas and schema elements. • The privilege to create schemas, tables, and other constructs must be explicitly granted to the relevant user accounts by the system administrator or DBA.
  • 66. DATABASE LANGUAGES 1. Data Definition Language (DDL): ▫ It is used to specify a database conceptual schema using set of definitions. ▫ It supports the definition or declaration of database objects. ▫ The more common DDL commands are  a.CREATE TABLE:  ALTER TABLE  DROP TABLE  TRUNCATE  COMMENT  RENAME
  • 67. 2. Data Manipulation Language (DML) ▫ It provides a set of operations to support the basic data manipulation operations on the data held in the database. ▫ It is used to query, update or retrieve data stored in a database. ▫ Some of the tasks that come under DML are  SELECT  Used to query and display data from a database.  INSERT  Adds new rows to a table.  UPDATE  Changes an existing value in a column or group of columns in a table.  DELETE:  Removes a specified row or set of rows from a table
  • 68. Data Control Language • DCL stands for Data Control Language. ▫ It is used to retrieve the stored or saved data. ▫ Grant: It is used to give user access privileges to a database. ▫ Revoke: It is used to take back permissions from the user.
  • 69. Transaction Control Language • TCL is used to run the changes made by the DML statement. ▫ Commit: It is used to save the transaction on the database. ▫ Rollback: It is used to restore the database to original since the last Commit.
  • 70. SQL Data Definition • The set of relations in a database are specified using a data-definition language (DDL) • The SQL DDL allows specification of not only a set of relations, but also information about each relation, including: ▫ The schema for each relation. ▫ The types of values associated with each attribute. ▫ The integrity constraints. ▫ The set of indices to be maintained for each relation. ▫ The security and authorization information for each relation. ▫ The physical storage structure of each relation on disk.
  • 71. Basic Schema Definition: CREATE TABLE Command in SQL • CREATE TABLE command is used to specify a new relation by giving it a name and specifying its attributes and initial constraints. • The attributes are specified first, and each attribute is given a name, a data type to specify its domain of values, and any attribute constraints, such as NOT NULL. • The key, entity integrity, and referential integrity constraints can be specified within the CREATE TABLE statement
  • 72. CREATION OF TABLES • The SQL CREATE TABLE statement is used to create a new table. • Syntax ▫ CREATE TABLE table_name( ▫ column1 datatype, ▫ column2 datatype, ▫ column3 datatype, ..... ▫ columnN datatype );
  • 73. Attribute Data Types and Domains in SQL • The basic data types available for attributes include ▫ numeric, ▫ char ▫ integer ▫ Boolean, ▫ date, and time ▫ Varchar
  • 74. • CREATE TABLE CUSTOMERS • ( ID INTEGER , • NAME VARCHAR (20), • AGE INTEGER, • ADDRESS CHAR (25) , • SALARY INTEGER);
  • 75. • CREATE TABLE CUSTOMERS • ( ID INTEGER NOT NULL, • NAME VARCHAR (20) NOT NULL, • AGE INT NOT NULL, • ADDRESS CHAR (25) , • SALARY INTEGER);
  • 76. Specifiying Key and Referiential • PRIMARY KEY ▫ specifies one or more attributes that make up the primary key of a relation. ▫ If a primary key has a single attribute, the clause can follow the attribute directly
  • 77. Primary Key Eg: • CREATE TABLE STUDENT • ( ROLL_NO INTEGER PRIMARY KEY, • STU_NAME VARCHAR (35), • STU_AGE INTEGER, • STU_ADDRESS VARCHAR (20));
  • 78. Primary Key Eg2: • CREATE TABLE STUDENT • ( ROLL_NO INTEGER NOT NULL, • STU_NAME VARCHAR (35) NOT NULL, STU_AGE INTEGER NOT NULL, • STU_ADDRESS VARCHAR (235), • PRIMARY KEY (ROLL_NO) );
  • 79. • UNIQUE The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns
  • 80. • CREATE TABLE Persons ( Personid integer UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) );
  • 81. DEFAULT constarint • CREATE TABLE tablename ( Columnname DEFAULT 'defaultvalue' ); • Eg: ▫ CREATE TABLE Geeks ▫ ( ID integer NOT NULL, ▫ Name varchar(255), ▫ Age integer, ▫ Location varchar(255) DEFAULT 'Noida'); ▫ INSERT INTO Geeks VALUES (4, 'Mira', 23, 'Delhi'); INSERT INTO Geeks VALUES (5, 'Hema', 27); INSERT INTO Geeks VALUES (6, 'Neha', 25, ‘Bihar'); INSERT INTO Geeks VALUES (7, 'Khushi', 26);
  • 82. FOREIGN KEY Constraint • A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. • The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.
  • 83. • CREATE TABLE Persons ( PersonID integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY(PersonID));
  • 84. • CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Per sons(PersonID) );
  • 85. Specifying Constraints on Tuples Using CHECK • CHECK clauses is specified at the end of a CREATE TABLE statement • These can be called tuple-based constraints because they apply to each tuple individually and are checked whenever a tuple is inserted or modified
  • 86. • The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK constraint ensures that the age of a person must be 18, or older:
  • 87. ALTER TABLE • The SQL ALTER TABLE command is used to add, delete ,modify or rename columns in an existing table. • The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows.
  • 88. Eg: • Existing • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY(Personid));
  • 89. • ALTER TABLE Persons ADD( Age integer); • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 90. • ALTER TABLE table_name ADD( column_name1 datatype1, column-name2 datatype2, column-name3 datatype3);
  • 91. • The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows. • The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows.
  • 92. • ALTER TABLE Persons DROP COLUMN( Age ); • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 93. • ALTER TABLE Persons MODIFY( Address char(255 ); • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 94. • ALTER TABLE Persons MODIFY( Address varchar(300); • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(300), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 95. • ALTER TABLE Persons RENAME address TO location; • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), location varchar(300), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 96. DROP TABLE • The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table. • You should be very careful while using this command because once a table is deleted then all the information available in that table will also be lost forever.
  • 97. • DROP TABLE Persons; • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), Age integer, PRIMARY KEY(Personid));
  • 99. INSERT Command • INSERT is used to add a single tuple to a relation. • We must specify the relation name and a list of values for the tuple. • The values should be listed in the same order in which the corresponding attributes were specified in the CREATE TABLE command.
  • 100. • INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...); • INSERT INTO table_name VALUES (value1, value2, value3, ...);
  • 101. • CREATE TABLE Persons ( Personid integer, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255)); • INSERT INTO Persons values (1,’Nair’,’Rajiv’,’Heaven’,’Bang lore’); • INSERT INTO Persons (Lname,City,Id,Fname,Addres s) values (’Nair’, ’Banglore’,1,’Rajiv’,’Heaven’,);
  • 102. • INSERT INTO Persons values (1,’Nair’,’Rajiv’,’Heaven’,’Banglore’); • INSERT INTO Persons (Lname,City,Id,Fname,Address) values (’Nair’, ’Banglore’,1,’Rajiv’,’Heaven’,);
  • 103. The DELETE Command • The DELETE command removes tuples from a relation. • It includes a WHERE clause, to select the tuples to be deleted. • Tuples are explicitly deleted from only one table at a time.
  • 105. • A missing WHERE clause specifies that all tuples in the relation are to be deleted; • the table remains in the database as an empty table. • DROP TABLE command is used to remove the table definition
  • 106. TRUNCATE TABLE COMMAND • The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. • You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.
  • 107. The UPDATE Command • The UPDATE command is used to modify attribute values of one or more selected tuples. • WHERE clause in the UPDATE command selects the tuples to be modified from a single relation
  • 112. 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. • Relational algebra is performed recursively on a relation and intermediate results are also considered as relations.
  • 113. • These operations enable a user to specify basic retrieval requests as relational algebra expressions. • A sequence of relational algebra operations forms a relational algebra expression, whose result will also be a relation that represents the result of a database query
  • 114. Types of Relational operation
  • 115. • Unary Relational Operations ▫ SELECT (symbol: σ) ▫ PROJECT (symbol: π) ▫ RENAME (symbol: ρ)
  • 116. • Relational Algebra Operations From Set Theory ▫ UNION (υ) ▫ INTERSECTION ( ), ▫ DIFFERENCE (-) ▫ CARTESIAN PRODUCT ( x ) • Binary Relational Operations ▫ JOIN ▫ DIVISION
  • 117. The SELECT Operation • The select operation selects tuples that satisfy a given predicate. • It is denoted by sigma (σ). • Notation: σ p(r) • Where: ▫ σ is used for selection prediction r is used for relation p is used as a propositional logic formula which may use connectors like: AND OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >, ≤.
  • 118. LOAN Relation BRANCH_NAME LOAN_NO AMOUNT Downtown L-17 1000 Redwood L-23 2000 Perryride L-15 1500 Downtown L-14 1500 Mianus L-13 500 Roundhill L-11 900 Perryride L-16 1300
  • 119. σ BRANCH_NAME="perryride" (LOAN) BRANCH_NAME LOAN_NO AMOUNT Perryride L-15 1500 Perryride L-16 1300
  • 120. • Select the EMPLOYEE tuples whose department is 4, or those whose salary is greater than $30,000
  • 121. • Clauses can be connected by the standard Boolean operators and, or, and not to form a general selection condition
  • 122. • Select the tuples for all employees who either work in department 4 and make over $25,000 per year, or work in department 5 and make over $30,000,
  • 123. Commutative Property of SELECT • SELECT operation is commutative • a sequence of SELECTs can be applied in any order. • we can always combine a cascade (or sequence) of SELECT operations into a single SELECT operation with a conjunctive (AND) condition; that is,
  • 124. Project Operation: • This operation shows the list of those attributes that we wish to appear in the result. Rest of the attributes are eliminated from the table. • It is denoted by ∏. • Notation: ∏ A1, A2, An (r) • Where ▫ A1, A2, A3 is used as an attribute name of relation r.
  • 125. CUSTOMER RELATION NAME STREET CITY Jones Main Harrison Smith North Rye Hays Main Harrison Curry North Rye Johnson Alma Brooklyn Brooks Senator Brooklyn
  • 126. ∏ NAME, CITY (CUSTOMER) NAME CITY Jones Harrison Smith Rye Hays Harrison Curry Rye Johnson Brooklyn Brooks Brooklyn
  • 127. Duplicate Elimination in PROJECT • The PROJECT operation removes any duplicate tuples, so the result of the PROJECT operation is a set of distinct tuples, and hence a valid relation. • This is known as duplicate elimination.
  • 128. Rename Operation: • The rename operation is used to rename the output relation. It is denoted by rho (ρ). • Example: We can use the rename operator to rename STUDENT relation to STUDENT1. ▫ ρ(STUDENT1, STUDENT)
  • 129. RENAME Operation General form • RENAME operation when applied to a relation R of degree n is denoted by any of the following three forms • symbol ρ (rho) is used to denote the RENAME operator, • S is the new relation name, and • B1, B2, ..., Bn are the new attribute names. ▫ The first expression renames both the relation and its attributes, ▫ the second renames the relation only, and ▫ the third renames the attributes only. • If the attributes of R are (A1, A2, ..., An) in that order, then each Ai is renamed as Bi.
  • 130. Example- In-Line relational algebra expression • retrieve the first name, last name, and salary of all employees who work in department number 5, we must apply a SELECT and a PROJECT operation
  • 132. Union Operation: • Suppose there are two tuples R and S. The union operation contains all the tuples that are either in R or S or both in R & S. • It eliminates the duplicate tuples. It is denoted by . ∪ • Notation: R S ∪ • A union operation must hold the following condition: ▫ R and S must have the attribute of the same number. ▫ Duplicate tuples are eliminated automatically.
  • 133. DEPOSITOR RELATION CUSTOMER_NAME ACCOUNT_NO Johnson A-101 Smith A-121 Mayes A-321 Turner A-176 Johnson A-273 Jones A-472 Lindsay A-284
  • 134. BORROW RELATION CUSTOMER_NAME LOAN_NO Jones L-17 Smith L-23 Hayes L-15 Jackson L-14 Curry L-93 Smith L-11 Williams L-17
  • 135. ∏ CUSTOMER_NAME (BORROW) ∏ CUSTOMER_NAME (DEPOSIT ∪ OR) CUSTOMER_NAME Johnson Smith Hayes Turner Jones Lindsay Jackson Curry Williams Mayes
  • 136. Set Intersection: • Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in both R & S. • It is denoted by intersection . ∩ • Notation: R S ∩
  • 137. ∏ CUSTOMER_NAME (BORROW) ∏ CUSTOM ∩ ER_NAME (DEPOSITOR) CUSTOMER_NAME Smith Jones
  • 138. Set Difference: • Suppose there are two tuples R and S. The set intersection operation contains all tuples that are in R but not in S. • It is denoted by intersection minus (-). • Notation: R - S • The MINUS operation is not commutative; that is, in general,
  • 139. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR) CUSTOMER_NAME Jackson Hayes Willians Curry
  • 140. Cartesian product (CROSS PRODUCT) OR CROSS JOIN • The Cartesian product is used to combine each row in one table with each row in the other table. It is also known as a cross product. • It is denoted by X. • Notation: E X D • This is also a binary set operation, but the relations on which it is applied do not have to be union compatible
  • 141. EMPLOYEE DEPARTMENT EMP_ID EMP_NA ME EMP_DEP T 1 Smith A 2 Harry C 3 John B DEPT_NO DEPT_NAME A Marketing B Sales C Legal
  • 142. EMPLOYEE X DEPARTMENT EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAM E 1 Smith A A Marketing 1 Smith A B Sales 1 Smith A C Legal 2 Harry C A Marketing 2 Harry C B Sales 2 Harry C C Legal 3 John B A Marketing 3 John B B Sales 3 John B C Legal
  • 143. Join Operations: • A Join operation combines related tuples from different relations, if and only if a given join condition is satisfied. • Outer Join: • The outer join operation is an extension of the join operation. It is used to deal with missing information.
  • 144. EMPLOYEE SALARY EMP_CODE EMP_NAME 101 Stephan 102 Jack 103 Harry EMP_CODE SALARY 101 50000 102 30000 103 25000
  • 145. (EMPLOYEE SALARY) ⋈ EMP_CODE EMP_NAME SALARY 101 Stephan 50000 102 Jack 30000 103 Harry 25000
  • 146. EMPLOYEE FACT_WORKERS EMP_NA ME STREET CITY Ram Civil line Mumbai Shyam Park street Kolkata Ravi M.G. Street Delhi Hari Nehru nagar Hyderaba d EMP_NA ME BRANCH SALARY Ram Infosys 10000 Shyam Wipro 20000 Kuber HCL 30000 Hari TCS 50000
  • 147. (EMPLOYEE FACT_WORKERS) ⋈ EMP_NAME STREET CITY BRANCH SALARY Ram Civil line Mumbai Infosys 10000 Shyam Park street Kolkata Wipro 20000 Hari Nehru nagar Hyderabad TCS 50000
  • 148. • An outer join is basically of three types: • Left outer join • Right outer join • Full outer join
  • 149. Left outer join: • Left outer join contains the set of tuples of all combinations in R and S that are equal on their common attribute names. • In the left outer join, tuples in R have no matching tuples in S. • It is denoted by . ⟕
  • 150. EMPLOYEE FACT_WORKERS ⟕ EMP_NAME STREET CITY BRANCH SALARY Ram Civil line Mumbai Infosys 10000 Shyam Park street Kolkata Wipro 20000 Hari Nehru street Hyderabad TCS 50000 Ravi M.G. Street Delhi NULL NULL
  • 151. Right outer join: • Right outer join contains the set of tuples of all combinations in R and S that are equal on their common attribute names. • In right outer join, tuples in S have no matching tuples in R. • It is denoted by . ⟖
  • 152. EMPLOYEE FACT_WORKERS ⟖ EMP_NAME BRANCH SALARY STREET CITY Ram Infosys 10000 Civil line Mumbai Shyam Wipro 20000 Park street Kolkata Hari TCS 50000 Nehru street Hyderabad Kuber HCL 30000 NULL NULL
  • 153. Full outer join: • Full outer join is like a left or right join except that it contains all rows from both tables. • In full outer join, tuples in R that have no matching tuples in S and tuples in S that have no matching tuples in R in their common attribute name. • It is denoted by . ⟗
  • 154. EMPLOYEE FACT_WORKERS ⟗ EMP_NAME STREET CITY BRANCH SALARY Ram Civil line Mumbai Infosys 10000 Shyam Park street Kolkata Wipro 20000 Hari Nehru street Hyderabad TCS 50000 Ravi M.G. Street Delhi NULL NULL Kuber NULL NULL HCL 30000
  • 155. Natural Join: • A natural join is the set of tuples of all combinations in R and S that are equal on their common attribute names. • It is denoted by . ⋈
  • 156. EMPLOYEE SALARY EMP_CODE EMP_NAME 101 Stephan 102 Jack 103 Harry EMP_CODE SALARY 101 50000 102 30000 103 25000
  • 157. ∏EMP_NAME, SALARY (EMPLOYEE SALARY) ⋈ EMP_NAME SALARY Stephan 50000 Jack 30000 Harry 25000
  • 158. Equi join: • It is also known as an inner join. It is the most common join. • It is based on matched data as per the equality condition. • The equi join uses the comparison operator(=). • In the result of an EQUIJOIN we always have one or more pairs of attributes that have identical values in every tuple
  • 159. student ROLL_NO NAME ADDRESS PHONE AGE 1 RAM DELHI 9455123451 18 2 RAMESH GURGAON 9652431543 18 3 SUJIT ROHTAK 9156253131 20 4 SURESH DELHI 9156768971 18
  • 160. employee EMP_NO NAME ADDRESS PHONE AGE 1 RAM DELHI 9455123451 18 5 NARESH HISAR 9782918192 22 6 SWETA RANCHI 9852617621 21 4 SURESH DELHI 9156768971 18
  • 161. Select students whose ROLL_NO is equal to EMP_NO of employees • STUDENT⋈STUDENT.ROLL_NO=EMPLOYEE.EMP_NOEM PLOYEE ROLL_NO NAME ADDRESS PHONE AGE 1 RAM DELHI 9455123451 18 4 SURESH DELHI 9156768971 18
  • 163. Division Operation • if you have two relations R and S, then, if U is a relation defined as the cartesian product of them: U = R x S. the division is the operator such that: U ÷ R = S.