Unit-3

The Relational Data Model and Relational Database Constraints

Relational Model Concepts
•	The relational Model of Data is based on the concept of a Relation.

•	A Relation is a mathematical concept based on the ideas of sets.

•	The strength of the relational approach to data management comes from the formal foundation provided by the theory of relations.

INFORMAL DEFINITIONS
•	RELATION:  A table of values

*	A relation may be thought of as a set of rows.
*	A relation may alternately be though of as a set of 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.
*	Sometimes row-ids or sequential numbers are assigned to identify the rows in the table.
*	Each column typically is called by its column name or column header or attribute name.
FORMAL DEFINITIONS
•	A Relation may be defined in multiple ways.
•	The Schema of a Relation: R (A1, A2, .....An)
	Relation schema R is defined over attributes A1, A2, .....An
  	For Example -
		CUSTOMER (Cust-id, Cust-name, Address, Phone#)

	Here, CUSTOMER is a relation defined over the four attributes Cust-id, Cust-name, Address, Phone#,  each of which has a domain or a set of valid values.  For example, the domain of Cust-id is 6 digit numbers.
•	A tuple is an ordered set of values
•	Each value is derived from an appropriate domain.
•	Each row in the CUSTOMER table may be referred to as a tuple in the table and would consist of four values.
*	<632895, "John Smith", "101 Main St. Atlanta, GA  30332", "(404) 894-2000"> 
is a tuple belonging to the CUSTOMER relation.
•	A relation may be regarded as a set of tuples (rows).
•	Columns in a table are also called attributes of the relation.

•	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 monthname, date, year or yyyy-mm-dd, or dd mm,yyyy etc.
•	An attribute designates the role played by the domain. E.g., the domain Date may be used to define attributes “Invoice-date” and “Payment-date”.

CHARACTERISTICS OF RELATIONS
•	Ordering of tuples in a relation r(R): The tuples are not  considered to be ordered, even though they appear to be in the tabular form.
•	 Ordering of attributes in a relation schema R (and of values within each tuple): We will consider the attributes in R(A1, A2, ..., An) and the values in t=<v1, v2, ..., vn> to be ordered .
	(However, a more general alternative definition  of relation does not require this ordering).
•	 Values in a tuple: All values are considered atomic  (indivisible). A special null value is used to represent values that are unknown or inapplicable to certain tuples. 

Relational Integrity Constraints
•	Constraints are conditions  that must hold on all  valid relation instances. There are three main types of constraints:
*	Key constraints
*	Entity integrity constraints
*	Referential integrity constraints 
Key Constraints
•	Superkey of R: A set of attributes SK of R such that no two tuples in any valid relation instance r(R)  will have the same value for SK.  That is, for any distinct tuples t1 and t2 in r(R), t1[SK]  t2[SK].
•	Key of R: A "minimal" superkey; that is, a superkey K such that removal of any attribute from K results in a set of attributes that is not a superkey.
Example: The CAR relation schema:
CAR(State, Reg#, SerialNo, Make, Model, Year)
has two keys Key1 = {State, Reg#}, Key2 = {SerialNo}, which are also superkeys. {SerialNo, Make} is a superkey but not  a key.
•	If a relation has several  candidate keys, one is chosen arbitrarily to be the primary key. The primary key attributes are underlined.

Key Constraints 

Entity Integrity
•	Relational Database Schema: A set S of relation schemas that belong to the same database. S is the name of the database.
S = {R1, R2, ..., Rn}
•	Entity Integrity: The primary key attributes PK of each relation schema R in S cannot have null values in any tuple of r(R). This is because primary key values are used to identify the individual tuples.
t[PK]  null for any tuple t in r(R)
•	 Note: Other attributes of R may be similarly constrained to disallow null values, even though they are not members of the primary key.
Referential Integrity
•	A constraint involving two relations (the previous constraints involve a single  relation).
•	Used to specify a relationship  among tuples in two relations: the referencing relation and the referenced relation.
•	Tuples in the referencing relation  R1 have attributes FK (called foreign key attributes) that reference the primary key attributes PK of the referenced relation  R2. A tuple t1 in R1 is said to reference a tuple t2 in R2 if t1[FK] = t2[PK].
•	A referential integrity constraint can be displayed in a relational database schema as a directed arc from R1.FK to R2. 
Statement of the constraint
The value in the foreign key column (or columns) FK of the the referencing relation R1 can be either:
	  (1) a value of an existing primary key value of the corresponding primary key PK in the referenced relation R2,, or..
 	 (2) a null.
Other Types of Constraints
Semantic Integrity Constraints:
*	E.g., “the max. no. of hours per employee for all projects he or she works on is 56 hrs per week”
*	A constraint specification language may have to be used to express these
*	SQL allows triggers and assertion to allow for some of these
Update Operations on Relations
•	INSERT a tuple.
•	DELETE a tuple.
•	MODIFY a tuple.
 
•	Integrity constraints should not be violated by the update operations.
•	Several update operations may have to be grouped together.
•	Updates may propagate to cause other updates automatically. This may be necessary to maintain integrity constraints.
Update Operations on Relations
•	In case of integrity violation, several actions can be taken:
*	Cancel the operation that causes the violation (REJECT option)
*	Perform the operation but inform the user of the violation
*	Trigger additional updates so the violation is corrected (CASCADE option, SET NULL option)
*	Execute a user-specified error-correction routine 
The Relational Algebra and Calculus

Relational Algebra Overview
*	Relational algebra is the basic set of operations for the relational model
*	These operations enable a user to specify basic retrieval requests (or queries)
*	The result of an operation is a new relation, which may have been formed from one or more input relations
*	This property makes the algebra “closed” (all objects in relational algebra are relations)
*	The algebra operations thus produce new relations
*	These can be further manipulated using operations of the same algebra
*	A sequence of relational algebra operations forms a relational algebra expression
*	The result of a relational algebra expression is also a relation that represents the result of a database query (or retrieval request)
*	Relational Algebra consists of several groups of operations
*	Unary Relational Operations
*	SELECT (symbol:  (sigma))
*	PROJECT (symbol: (pi))
*	RENAME (symbol:  (rho))
*	Relational Algebra Operations From Set Theory
*	UNION (  ), INTERSECTION ( ), DIFFERENCE (or MINUS, – )
*	CARTESIAN PRODUCT ( x )
*	Binary Relational Operations
*	JOIN (several variations of JOIN exist)
*	DIVISION
*	Additional Relational Operations
*	OUTER JOINS, OUTER UNION
*	AGGREGATE FUNCTIONS (These compute summary of information: for example, SUM, COUNT, AVG, MIN, MAX)
Unary Relational Operations: SELECT
*	The SELECT operation (denoted by  (sigma)) is used to select a subset of the tuples from a relation based on a selection condition.
*	The selection condition acts as a filter
*	Keeps only those tuples that satisfy the qualifying condition
*	Tuples satisfying the condition are selected whereas the other tuples are discarded (filtered out)
*	Examples: 
*	Select the EMPLOYEE tuples whose department number is 4:
 DNO = 4 (EMPLOYEE)
*	Select the employee tuples whose salary is greater than $30,000:
 SALARY > 30,000 (EMPLOYEE)
Unary Relational Operations: PROJECT
*	PROJECT Operation is denoted by (pi) 
*	This operation keeps certain columns (attributes) from a relation and discards the other columns.
*	PROJECT creates a vertical partitioning
*	The list of specified columns (attributes) is kept in each tuple
*	The other attributes in each tuple are discarded
*	Example: To list each employee’s first and last name and salary, the following is used:
LNAME, FNAME,SALARY(EMPLOYEE)
*	To 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
*	We can write a single relational algebra expression as follows: 
*	FNAME, LNAME, SALARY( DNO=5(EMPLOYEE))
*	OR We can explicitly show the sequence of operations, giving a name to each intermediate relation:
*	DEP5_EMPS   DNO=5(EMPLOYEE)
*	RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)	
Unary Relational Operations: RENAME
*	The RENAME operator is denoted by  (rho)
*	In some cases, we may want to rename the attributes of a relation or the relation name or both
*	Useful when a query requires multiple operations
*	Necessary in some cases (see JOIN operation later)
*	UNION Operation
*	Binary operation, denoted by  
*	The result of R  S, is a relation that includes all tuples that are either in R or in S or in both R and S
*	Duplicate tuples are eliminated
*	The two operand relations R and S must be “type compatible” (or UNION compatible)
*	R and S must have same number of attributes
*	Each pair of corresponding attributes must be type compatible (have same or compatible domains)

*	Example: 
*	To retrieve the social security numbers of all employees who either work in department 5 (RESULT1 below) or directly supervise an employee who works in department 5 (RESULT2 below)
*	We can use the UNION operation as follows:
DEP5_EMPS  DNO=5 (EMPLOYEE)
RESULT1   SSN(DEP5_EMPS)
RESULT2(SSN)  SUPERSSN(DEP5_EMPS)
RESULT  RESULT1  RESULT2
*	The union operation produces the tuples that are in either RESULT1 or RESULT2 or both

Relational Algebra Operations from Set Theory: INTERSECTION
*	INTERSECTION is denoted by 
*	The result of the operation R  S, is a relation that includes all tuples that are in both R and S
*	The attribute names in the result will be the same as the attribute names in R
*	The two operand relations R and S must be “type compatible”

Relational Algebra Operations from Set Theory: SET DIFFERENCE (cont.) 
*	SET DIFFERENCE (also called MINUS or EXCEPT) is denoted by – 
*	The result of R – S, is a relation that includes all tuples that are in R but not in S
*	The attribute names in the result will be the same as the attribute names in R
*	The two operand relations R and S must be “type compatible”

Example to illustrate the result of UNION, INTERSECT, and DIFFERENCE
Some properties of UNION, INTERSECT, and DIFFERENCE
*	Notice that both union and intersection are commutative operations; that is
*	R  S = S  R, and R  S = S  R
*	Both union and intersection can be treated as n-ary operations applicable to any number of relations as both are associative operations; that is
*	R  (S  T) = (R  S)  T
*	(R  S)  T = R  (S  T)
*	The minus operation is not commutative; that is, in general
*	R – S ≠ S – R

Relational Algebra Operations from Set Theory: CARTESIAN PRODUCT
*	CARTESIAN (or CROSS) PRODUCT Operation
*	This operation is used to combine tuples from two relations in a combinatorial fashion.
*	Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm)
*	Result is a relation Q with degree n + m attributes:
*	Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
*	The resulting relation state has one tuple for each combination of tuples—one from R and one from S. 
*	Hence, if R has nR tuples (denoted as |R| = nR ), and S has nS tuples, then R x S will have nR * nS tuples.
*	The two operands do NOT have to be "type compatible”
*	Generally, CROSS PRODUCT is not a meaningful operation
*	Can become meaningful when followed by other operations
*	Example (not meaningful):
*	FEMALE_EMPS   SEX=’F’(EMPLOYEE)
*	EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
*	EMP_DEPENDENTS  EMPNAMES x DEPENDENT

Binary Relational Operations: JOIN
*	JOIN Operation (denoted by     )
*	The sequence of CARTESIAN PRODECT followed by SELECT is used quite commonly to identify and select related tuples from two relations
*	A special operation, called JOIN combines this sequence into a single operation
*	This operation is very important for any relational database with more than a single relation, because it allows us combine related tuples from various relations 
*	Example: Suppose that we want to retrieve the name of the manager of each department.
*	To get the manager’s name, we need to combine each DEPARTMENT tuple with the EMPLOYEE tuple whose SSN value matches the MGRSSN value in the department tuple. 
*	We do this by using the join           operation.

*	DEPT_MGR  DEPARTMENT   MGRSSN=SSN EMPLOYEE
*	MGRSSN=SSN is the join condition
*	Combines each department record with the employee who manages the department
*	The join condition can also be specified as DEPARTMENT.MGRSSN= EMPLOYEE.SSN

EQUIJOIN
*	EQUIJOIN Operation
*	The most common use of join involves join conditions with equality comparisons only
*	Such a join, where the only comparison operator used is =, is called an EQUIJOIN.
*	In the result of an EQUIJOIN we always have one or more pairs of attributes (whose names need not be  identical) that have identical values in every tuple. 
*	The JOIN seen in the previous example was an EQUIJOIN.
NATURAL JOIN Operation
*	NATURAL JOIN Operation 
*	Another variation of JOIN called NATURAL JOIN — denoted by * — was created to get rid of the second (superfluous) attribute in an EQUIJOIN condition.
*	because one of each pair of attributes with identical values is superfluous
*	The standard definition of natural join requires that the two join attributes, or each pair of corresponding join attributes, have the same name in both relations
*	If this is not the case, a renaming operation is applied first.	                    	
Binary Relational Operations: DIVISION
*	DIVISION Operation
*	The division operation is applied to two relations 
*		R(Z)  S(X), where X subset Z. Let Y = Z - X (and hence Z = X  Y); that is, let Y be the set of attributes of R that are not attributes of S. 

*	The result of DIVISION is a relation T(Y) that includes a tuple t if tuples tR appear in R with tR [Y] = t, and with
*	tR [X] = ts for every tuple ts in S. 

*	For a tuple t to appear in the result T of the DIVISION, the values in t must appear in R in combination with every tuple in S. 		
*	
Aggregate Functions and Grouping
*	A type of request that cannot be expressed in the basic relational algebra is to specify mathematical aggregate functions on collections of values from the database. 
*	Examples of such functions include retrieving the average or total salary of all employees or the total number of employee tuples.
*	These functions are used in simple statistical queries that summarize information from the database tuples.
*	Common functions applied to collections of numeric values include
*	SUM, AVERAGE, MAXIMUM, and MINIMUM.
*	The COUNT function is used for counting tuples or values.
Aggregate Function Operation
*	Use of the Aggregate Functional operation ℱ
*	ℱMAX Salary (EMPLOYEE) retrieves the maximum salary value from the EMPLOYEE relation
*	ℱMIN Salary (EMPLOYEE) retrieves the minimum Salary value from the EMPLOYEE relation
*	ℱSUM Salary (EMPLOYEE) retrieves the sum of the Salary from the EMPLOYEE relation
*	 ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count (number) of employees and their average salary
*	Note: count just counts the number of rows, without removing duplicates

*	The OUTER JOIN Operation
*	In NATURAL JOIN and EQUIJOIN, tuples without a matching (or related) tuple are eliminated from the join result
*	Tuples with null in the join attributes are also eliminated
*	This amounts to loss of information.
*	A set of operations, called OUTER joins, can be used when we want to keep all the tuples in R, or all those in S, or all those in both relations in the result of the join, regardless of whether or not they have matching tuples in the other relation.

*	The left outer join operation keeps every tuple in the first or left relation R in R      S; if no matching tuple is found in S, then the attributes of S in the join result are filled or “padded” with null values.
*	A similar operation, right outer join, keeps every tuple in the second or right relation S in the result of R       S.
*	A third operation, full outer join, denoted by               keeps all tuples in both the left and the right relations when no matching tuples are found, padding them with null values as needed. 

*	OUTER UNION Operations
*	The outer union operation was developed to take the union of tuples from two relations if the relations are not type compatible. 
*	This operation will take the union of tuples in two relations R(X, Y) and S(X, Z) that are partially compatible, meaning that only some of their attributes, say X, are type compatible. 
*	The attributes that are type compatible are represented only once in the result, and those attributes that are not type compatible from either relation are also kept in the result relation T(X, Y, Z).