RDBMS

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 61

RDBMS

 A database is a collection of 1 or more ‘relations’, where each


relation is a table with rows and columns.
 The advantages of the relational model over the older data
models are
 It is simple and elegant.
 Simple data representation.
 The ease with which even complex queries can be expressed.
RELATION
 A relation consists of following fields:
1. Relation Schema:
 The relation schema describes the column heads for the
table. The schema specifies the relation’s name, the name of
each field (column, attribute) and the ‘domain’ of each field.
A domain is referred to in a relation schema by the domain
name and has a set of associated values.
 Example: Student information in a university database to
illustrate the parts of a relation schema. Students (Sid: string,
name: string, login: string, age: integer, gross: real) this says
that the field named ‘sid’ has a domain named ‘string’.
Relation Instance

2.Relation Instance:
 This is a table specifying the information. An instance of a relation is a set
of ‘tuples’, also called ‘records’, in which each tuple has the same number
of fields as the relation schemas. A relation instance can be thought of as
a table in which each tuple is a row and all rows have the same number of
fields.
sid Name login age Gross
1111 Dave dave@cs 19 1.2
2222 Jones Jones@cs 18 2.3
333 Smith smith@ee 18 3.4
4444 Smith smith@math 19 4
Relation
Degree
The number of fields/columns/attributes is called as ‘degree’. This is also
called as ‘arity’.
Cardinality:
The number of tuples/rows/records in a given relation is called as
cardinality of a relationsid Name login age Gross

1111 Dave dave@cs 19 1.2


2222 Jones Jones@cs 18 2.3

333 Smith smith@ee 18 3.4


4444 Smith smith@math 19 4

Example
In the above example, the degree of the relation is 5 and the cardinality is 4
Relational database and schema
Relational database
 It is a collection of relations with distinct relation names.
Relational database schema:
 It is the collection of schemas for the relations in the
database.
 Instance: An instance of a relational database is a
collection of relation instances, one per relation schema
in the database schema. Each relation instance must
satisfy the domain constraints in its schema.
Integrity constraints over relations

 An integrity constraint (IC) is a condition that is specified on a database


schema and restricts the data can be stored in an instance of the database.
Various restrictions on data that can be specified on a relational database
schema in the form of ‘constraints’. A DBMS enforces integrity constraints,
in that it permits only legal instances to be stored in the database.
 Integrity constraints are specified and enforced at different times as below.

1.When the DBA or end user defines a database schema, he or she specifies
the ICs that must hold on any instance of this database.
2.When a data base application is run, the DBMS checks for violations and
disallows changes to the data that violate the specified ICs. Legal Instance: If
the database instance satisfies all the integrity constraints specified on the
database schema.
Integrity constraints
The constraints can be classified into 4 types as
below.
1. Domain Constraints.
2. Key Constraints.
3. Entity Integrity Constraints.
4. Referential Integrity Constraints.
 
Domain constraints
 Domain constraints are the most elementary
form of integrity constraints.
 They are tested easily by the system whenever
a new data item is entered into the database.
 Domain constraints specify the set of possible
values that may be associated with an
attribute. Such constraints may also prohibit
the use of null values for particular attributes.
Key constraints
 A key constraint is a statement that a certain
minimal subset of the fields of a relation is a
unique identifier for a tuple.
 Example: The ‘students’ relation and the
constraint that no 2 students have the same
student id (sid).
Entity Integrity Constraints.

 This states that no primary key value can be


null and it must have a unique value.
 The primary key value is used to identify
individual tuples in a relation. Having null
values for the primary key implies that we
cannot identify some tuples.
Referential Integrity Constraint
 The Referential Integrity Constraint is specified
between 2 relations and is used to maintain
the consistency among tuples of the 2
relations.
 the referential integrity constraint states that
‘a tuple in 1 relation that refers to another
relation must refer to an existing tuple in that
relation.
Querying relational data

 A query is a statement requesting the retrieval of information. The portion of a

DML that involves information retrieval is called a query language.

 A DBMS provides a specialized language, called the query language, in which

queries can be posed. A very attractive feature of the relational model is that it

supports powerful query languages.


QUERIES IN RDBMS
Querying relational data
Relational Query Languages
 Relational query languages use relational algebra to break the user requests and instruct the
DBMS to execute the requests. It is the language by which user communicates with the database.
These relational query languages can be procedural or non-procedural.

Procedural Query Language


 A procedural query language will have set of queries instructing the DBMS to perform various
transactions in the sequence to meet the user request.
 For example, get_CGPA procedure will have various queries to get the marks of student in each
subject, calculate the total marks, and then decide the CGPA based on his total marks.
 This procedural query language tells the database what is required from the database and how to
get them from the database. Relational algebra is a procedural query language.

Non-Procedural Query Language


 Non-procedural queries will have single query on one or more tables to get result from the
database.
 For example, get the name and address of the student with particular ID will have single query
on STUDENT table. Relational Calculus is a non procedural language which informs what to do
with the tables, but doesn’t inform how to accomplish this.
Deferred mode and immediate mode
operations

Deferred Update
It is a technique for the maintenance of the transaction log files of the DBMS. It is also called NO-UNDO/REDO
technique. It is used for the recovery of the transaction failures which occur due to power, memory or OS
failures. Whenever any transaction is executed, the updates are not made immediately to the database. They
are first recorded on the log file and then those changes are applied once commit is done. This is called “Re-
doing” process. Once the rollback is done none of the changes are applied to the database and the changes in
the log file are also discarded. If commit is done before crashing of the system, then after restarting of the
system the changes that have been recorded in the log file are thus applied to the database. 

Immediate Update
It is a technique for the maintenance of the transaction log files of the DBMS. It is also called UNDO/REDO
technique. It is used for the recovery of the transaction failures which occur due to power, memory or OS
failures. Whenever any transaction is executed, the updates are made directly to the database and the log file
is also maintained which contains both old and new values. Once commit is done, all the changes get stored
permanently into the database and records in log file are thus discarded. Once rollback is done the old values
get restored in the database and all the changes made to the database are also discarded. This is called “Un-
doing” process. If commit is done before crashing of the system, then after restarting of the system the
changes are stored permanently in the database. 
Enforcing Integrity Constraints

There are 5 different referential actions:


1. CASCADE
2. RESTRICT
3. NO ACTION
4. SET NULL
5. SET DEFAULT
Enforcing Integrity Constraints
CASCADE

 ON DELETE CASCADE means that if the parent record is deleted, any child


records are also deleted.
 ON UPDATE CASCADE means that if the parent primary key is changed, the child
value will also change to reflect that.
 ON UPDATE CASCADE ON DELETE CASCADE means that if
you UPDATE OR DELETE the parent, the change is cascaded to the child.
 FOREIGN KEY (column name) REFERENCES parent table(column name)
on delete cascade on update cascade
Enforcing Integrity Constraints
RESTRICT
RESTRICT means that any attempt to delete
and/or update the parent will fail throwing an
error. This is the default behavior in the event that
a referential action is not explicitly specified.
For an ON DELETE or ON UPDATE that is not
specified, the default action is always RESTRICT`.
Enforcing Integrity Constraints
NO ACTION
The MySQL Server rejects the delete or update
operation for the parent table if there is a related
foreign key value in the referenced table.
Some database systems have deferred checks,
and NO ACTION is a deferred check. In MySQL,
foreign key constraints are checked immediately,
so NO ACTION is the same as RESTRICT.
Enforcing Integrity Constraints
SET NULL
Delete or update the row from the parent table,
and set the foreign key column or columns in the
child table to NULL.
Enforcing Integrity Constraints
SET DEFAULT
 Allows to specify a default value to which to
set the foreign key column(s) on an UPDATE or
a DELETE.
keys
Super key
• A super key is a set of attributes that can
identify each tuple uniquely in the given
relation.
• A super key is not restricted to have any
specific number of attributes.
• Thus, a super key may consist of any number
of attributes.
Super key
• Example
• Consider the following Student schema
• Student ( roll , name , gender, age , address , class , section )

• Given below are the examples of super keys since


each set can uniquely identify each student in the
Student table-
• ( roll , name , gender, age , address , class , section )
• ( class , section , roll )
• (class , section , roll , gender)
Candidate key
 A set of minimal attributes that can identify each tuple
uniquely in the given relation is called as a candidate key.
•  
• Consider the following Student schema-
• Student ( roll , name , gender, age , address , class , section )

•  
• Given below are the examples of candidate keys since
each set consists of minimal attributes required to identify
each student uniquely in the Student table-
• ( class , section , roll )
Candidate key
• All the attributes in a candidate key are sufficient as well
as necessary to identify each tuple uniquely.
• Removing any attribute from the candidate key fails in
identifying each tuple uniquely.
• The value of candidate key must always be unique.
• The value of candidate key can never be NULL.
• It is possible to have multiple candidate keys in a relation.
• Those attributes which appears in some candidate key are
called as prime attributes.
•  
Primary key
• It is the minimal of candidate key.
• The value of primary key can never be NULL.
• The value of primary key must always be unique.
• The values of primary key can never be changed
i.e. no updation is possible.
• The value of primary key must be assigned when
inserting a record.
• A relation is allowed to have only one primary key.
Foreign key
• It references the primary key in another
table.
Foreign key
 An attribute ‘X’ is called as a foreign key to some other
attribute ‘Y’ when its values are dependent on the values of
attribute ‘Y’.
 The attribute ‘X’ can assume only those values which are
assumed by the attribute ‘Y’.
 Here, the relation in which attribute ‘Y’ is present is called as
the referenced relation.
 The relation in which attribute ‘X’ is present is called as
the referencing relation.
 The attribute ‘Y’ might be present in the same table or in
some other table.
Composite Key
 

• A primary key comprising of multiple


attributes and not just a single attribute is
called as a composite key.
tables
• Sailors (sid: integer, sname: string, rating: integer, age: real)
• Boats (bid: integer, bname: string, color: string)
• Reserves (sid: integer, bid: integer, day: date)
Sailors table
• insert into sailors values(22,'dustin',7,45);
• insert into sailors values(29,'brutus',1,33);
• insert into sailors values(31,'lubber',79,55);
• insert into sailors values(32,'andy',8,25);
• insert into sailors values(58,'rusty',10,35);
• insert into sailors values(58,'buplb',10,35);
• insert into sailors values(58,'buplerb',10,35);
• insert into sailors values(22,'bb',10,35);
Boats table
• insert into boats values(101,'interlake','blue');
• insert into boats values(102,'interlake','red');
• insert into boats values(103,'clipper','green');
• insert into boats values(104,'marine','red');
 
Reserves table
• insert into reserves values(22,101,'2004-01-01');
• insert into reserves values(22,102,'2004-01-01');
• insert into reserves values(22,103,'2004-02-01');
• insert into reserves values(22,105,'2004-02-01');
• insert into reserves values(31,103,'2005-05-05');
• insert into reserves values(32,104,'2005-04-07');
 
views
 A view is a virtual table based on the result-set of an SQL
statement.
 A view contains rows and columns, just like a real table. The fields
in a view are fields from one or more real tables in the database.
 We can create a view by selecting fields from one or more tables
present in the database.
 A View can either have all the rows of a table or specific rows
based on certain condition.
 Views are a logical virtual table created by “select query” but the
result is not stored anywhere in the disk and every time we need
to fire the query when we need data, so always we get updated or
latest data from original tables.
views
 A view is a predefined query on one or more tables.
 Retrieving information from a view is done in the same manner
as retrieving from a table.
 With some views you can also perform DML operations (delete,
insert, update) on the base tables.
 Views don't store data, they only access rows in the base tables.
 user tables, user sequences, and user indexes are all views.
 view can hide the underlying base tables.
 By writing complex queries as a view, we can hide complexity
from an end user.
 View only allows a user to access certain rows in the base tables.
Creating views
A View can be created from a single table or
multiple tables.
CREATE VIEW view_name AS SELECT column1,
column2..... FROM table_name WHERE
condition;
Views
• SD table and SM Table
Creating views
• Creating View from a single table:
• CREATE VIEW Details AS SELECT NAME,
ADDRESS FROM SD WHERE S_ID < 5;
• To see the data in the View, we can query the
view in the same manner as we query a table.
• SELECT * FROM Details;
Creating View from multiple tables:

CREATE VIEW Marks AS SELECT SD.NAME,


SD.ADDRESS, SM.MARKS FROM SD, SM WHERE
SD.NAME = SM.NAME;
UPDATING VIEWS

 A view can be updated under certain conditions:


 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause
 the query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
CREATE OR REPLACE VIEW:
 Replace view_name AS SELECT
column1,coulmn2,..FROM table_name WHERE
condition;
 For example, if we want to update the view
Marks and add the field AGE to this View from
SM Table, we can do this as: CREATE OR
REPLACE VIEW Marks AS SELECT SD.NAME,
SD.ADDRESS, SM.MARKS,SM.AGE FROM
SD,SM WHERE SD.NAME = SM.NAME;
views
 Inserting a row
INSERT INTO View name(C1,C2...Cn) VALUES(V1,V2….Vn);
INSERT INTO Details(NAME, ADDRESS) VALUES("Suresh","Gurgaon");
 DELETING Rows
Deleting rows from a view is also as simple as deleting rows from a table. We
can use the DELETE statement of SQL to delete rows from a view. Also deleting
a row from a view first delete the row from the actual table and the change is
then reflected in the view.
 DELETE FROM view_name WHERE condition;
 DELETE FROM Details WHERE NAME="Suresh";
 DELETING VIEWS
We can delete or drop a View using the DROP statement.
DROP VIEW view_name;
Logical Data Base Design
1.Entity sets to tables

CREATE TABLE Employees


(ssn CHAR(11), name
CHAR(20), lot INTEGER,
PRIMARY KEY (ssn))
Logical Data Base Design
2.Relationship Sets to Tables

CREATE TABLE Works_In( ssn CHAR(1), did INTEGER, since DATE,


PRIMARY KEY (ssn, did), FOREIGN KEY (ssn) REFERENCES
Employees, FOREIGN KEY (did) REFERENCES Departments)
In translating a relationship set to a relation,attributes of the
relation must include
 Keys for each participating entity set (as foreign keys).
 This set of attributes forms a super key for the relation.
 All descriptive attributes.
Logical Data Base Design
• Review Key Constraints each dept has at most one
manager, according to the key constraint on Manages.

budget
did
Departments
Translation to relational model?
Many-to-Many
1-to-1
1-to Many
Many-to-1
Key Constraints name
since
dname
ssn lot did budget

• Consider Works_In:
Employees Manages Departments
An employee can
Key Constraint
work in many
departments; a dept
can have many
employees.
• In contrast, each dept
has at most one
manager, according to
the key constraint on
Manages. 1-to-1 Many-to 1 1-to-Many Many-to-Many
3.Translating ER Diagrams with Key
Constraints
• Translating ER Diagrams with Key Constraints
• CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY
(did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did)
REFERENCES Departments)
• Map relationship to a table
• Note that did is the key now!
• Separate tables for Employees and Departments.
• Since each department has a unique manager, we
could instead combine Manages and Departments.

CREATE TABLE Dept_Mgr( did INTEGER, dname


CHAR(20), budget REAL, ssn CHAR(11),
since DATE, PRIMARY KEY (did), FOREIGN
KEY (ssn) REFERENCES Employees)
Logical Data Base Design
• Review Participation Constraints Does every department have a manager?
• If so, this is a participation constraint the participation of Departments in Manages is said to be total (vs. partial).
• Every did value in Departments table must appear in a row of the Manages table (with a non-null ssn value!)

since
since
name
name
dname
dname
lot
budget
did
budget
did
ssn
Departments
Employees
Manages
Works_In
since
3.Translating ER Diagrams with participation
Constraints
• Participation Constraints in SQL We can capture
participation constraints involving one entity set in a
binary relationship, but little else (without resorting
to CHECK constraints).

CREATE TABLE Dept_Mgr( did INTEGER, dname


CHAR(20), budget REAL, ssn CHAR(11) NOT
NULL, since DATE, PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees, ON
DELETE NO ACTION)
Logical Data Base Design
• Review Weak EntitiesA weak entity can be identified uniquely only by
considering the primary key of another (owner) entity.
• Owner entity set and weak entity set must participate in a one-to-many
relationship set (1) owner, many weak entities).
• Weak entity set must have total participation in this identifying relationship set.

name
cost
pname
age
ssn
lot
Dependents
Policy
Employees
Weak Entities
 A weak entity can be identified uniquely only by
considering the primary key of another (owner)
entity.
Owner entity set and weak entity set must participate in
a one-to-many relationship set (1 owner, many weak
entity.

name
cost pname age
ssn lot

Primary Key
for weak entity
Employees Policy Dependents

Identifying Relationship Weak Entity


4.Translating Weak Entity Sets

• Translating Weak Entity Sets


• Weak entity set and identifying relationship set
are translated into a single table.
• When the owner entity is deleted, all owned weak
entities must also be deleted.

CREATE TABLE Dep_Policy ( pname CHAR(20),


age INTEGER, cost REAL, ssn CHAR(11) NOT
NULL, PRIMARY KEY (pname, ssn), FOREIGN
KEY (ssn) REFERENCES Employees, ON DELETE
CASCADE)
Logical Data Base Design
• Review ISA Hierarchies name ssn lot Employees hours_worked hourly_wages
ISAAs in C, or other PLs, attributes are
inherited.
• If we declare A ISA B, every A entity is also
considered to be a B entity.

contractid
Contract_Emps
Hourly_Emps Overlap constraints Can Joe be an Hourly_Emps
as well as a Contract_Emps entity?
(Allowed/disallowed)
• Covering constraints Does every Employees
entity also have to be an Hourly_Emps or a
Contract_Emps entity? (Yes/no)
name
ssn lot

class Hierarchies(IS A hierarchy) Employees

 Asin C++, or other PLs, attributes are hourly_wages hours_worked


inherited. ISA
contractid

we declare A ISA B, every A entity is also


 If
Hourly_Emps Contract_Emps
considered to be a B entity.

• Overlap constraints: Can Joe be an Hourly_Emps as well as a


Contract_Emps entity? (Allowed/disallowed)
• Covering constraints: Does every Employees entity also have to be
an Hourly_Emps or a Contract_Emps entity? (Yes/no)
• Reasons for using ISA:
– To add descriptive attributes specific to a subclass.
– To identify entitities that participate in a relationship.
5.Translating ISA Hierarchies to Relations

Translating ISA Hierarchies to Relations


 General approach 3 relations Employees, Hourly_Emps and
Contract_Emps.
 Hourly_Emps Every employee is recorded in
Employees. For hourly emps, extra info recorded
in Hourly_Emps (hourly_wages, hours_worked, ssn)
must delete Hourly_Emps tuple if referenced
Employees tuple is deleted).
 Queries involving all employees easy, those
involving just Hourly_Emps require a join to get
some attributes.
 Alternative Just Hourly_Emps and Contract_Emps.
 Hourly_Emps ssn, name, lot, hourly_wages,
hours_worked.
 Each employee must be in one of these two
subclasses.
Logical Data Base Design
• Review Binary vs. Ternary Relationships pname age.
• If each policy is owned by just 1 employee
• Key constraint on Policies would mean policy can
only cover 1 dependent!
• What are the additional constraints in the 2nd
diagram?

Dependents
Covers
Bad design
pname
age
Dependents
Purchaser
Better design
name
ssn lot

Aggregation Employees

 Used when we have to


model a relationship Monitors until
involving (entitity sets
Aggregation
and) a relationship set.
 Aggregation allows us started_on
dname
to treat a relationship pid pbudget did budget
set as an entity set for
purposes of Projects Sponsors Departments
participation in (other)
relationships.
Aggregation vs. ternary relationship:
 Monitors
 Monitors mapped to relationship,
is a distinct
table
 withlike any otherattribute.
a descriptive
relationship set.that each sponsorship
 Also, can say
 is monitored by at most one employee.
Translating ER diagrams with Aggregation
• Binary vs. Ternary Relationships
• CREATE TABLE Policies ( policyid INTEGER, cost REAL, ssn CHAR(11)
NOT NULL, PRIMARY KEY (policyid). FOREI N KEY (ssn) REFERENCES
Employees, ON DELETE CASCADE)
• The key constraints allow us to combine Purchaser
with Policies and Beneficiary with Dependents.
• Participation constraints lead to NOT NULL
constraints.

CREATE TABLE Dependents ( pname CHAR(20),


age INTEGER, policyid INTEGER, PRIMARY KEY (pname, policyid),
FOREIGN KEY (policyid) REFERENCES Policies, ON DELETE CASCADE);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy