Unit Ii DBMS 2024
Unit Ii DBMS 2024
Unit Ii DBMS 2024
Relational Model: Introduction to the Relational Model, Integrity Constraints over Relations,
Enforcing Integrity Constraints, Querying Relational Data, Logical Database Design: ER to
Relational, Introduction to Views, Destroying/Altering Tables and Views
Relational Algebra: Selection and Projection, Set Operations, Renaming, Joins, Division, More
Examples of Algebra Queries, Relational Calculus: Tuple Relational Calculus, Domain
Relational Calculus.
Relational Model was proposed by E.F Codd to model data in the form of relations or
tables. After designing the conceptual model of database using ER diagram, we need to
convert the conceptual model in the relational model which can be implemented using
any RDBMS (Relational Data Base Management System) like SQL, MY SQL etc.
The relational model is very simple and elegant; a database is a collection of one or more
relations, where each relation is a table with rows and columns.
This simple tabular representation enables even new users to understand the contentsof
a database, and it permits the use of simple, high-level languages to query the data.
Relational Model
Relational Model represents how date is stored in relational databases. A Relational database
stores data in the form ofrelations (tables).
Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS,
PHONE and AGE as shown in table.
Attribute: Attributes are the properties that define arelation. Ex: ROLL_NO, NAME
Tuple: Each row in a relation is known as tuple.
Ex:
1 Nishma Hyderabad 9455123451 28
ROLL_N
O
1
Null values: The value which is not known or unavailable is called NULL VALUE.
Itis represented by blank space.
Cardinality: The number of tuples is present in the relation is called as its cardinality.
Ex: The Cardinality of the STUDENT table is 4.
Concept Of Domain
The domain of a database is the set of all allowable values (or) attributes of the database.
Ex: Gender (Male, Female, Others).
Relation
A relation is defined as a set of tuples and attributes.
A relation consists of Relation schema and relation instance.
Relation schema: A relation schema represents the name of the relation with its attributes.
Ex: STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is
Relation schema for STUDENT.
Relation instance: The set of tuples of a relation at a particular instance of a time is called
Relation Instance.
An instance of Employee relation
Entity: An entity is an object in the real world that is distinguishable from other objects.
Entity set: An entity set is a collection of similar entities. The Employees entity
set with attributes ssn, name, and lot is shown in the following figure.
Types of attributes:
Degree of Relationship is the number of participating entities in a relationship defines the degree
of the relationship. Based on degree the relationships are categorized as
Unary = degree 1
Binary = degree 2
Ternary = degree 3
n-array = degree
Unary Relationship: A relationship with one entity set. It is like a relationship among 2 entities
of same entity set. Example: A professor ( in-charge) reports to another professor (Head Of the
Dept).
Binary Relationship: A relationship among 2 entity sets. Example: A professor teaches a
course and a course is taught by a professor.
Cardinality:
Defines the number of entities in one entity set, which can be associated with the number of
entities of other set via relationship set. Cardinality ratios are categorized into 4. They are.
One-to-One relationship: When only one instance of entities is associated with the
relationship, then the relationship is one-to-one relationship. Each entity in A is associated
with at most one entity in B and each entity in B is associated with at most one entity in A.
One-to-many relationship: When more than one instance of an entity is associated with a
relationship, then the relationship is one-to-many relationship. Each entity in A is associated
with zero or more entities in B and each entity in B is associated with at most one entity in A.
Many-to-one relationship: When more than one instance of entity is associated with the
relationship, then the relationship is many-to-one relationship. Each entity in A is associated
with at most one entity in B and each entity in B is associated with 0 (or) more entities in A.
Many-to-Many relationship: If more than one instance of an entity on the left and more
than one instance of an entity on the right can be associated with the relationship, then it depicts
many-to-many relationship. Each entity in A is associated with 0 (or) more entities in B and
each entity in B is associated with 0 (or) more entities in A.
Relationship Set:
A set of relationships of similar type is called a relationship set. Like entities, a relationship too
can have attributes. These attributes are called descriptive attributes.
In DBMS, constraints refer to limitations placed on data or data processes. This indicates that
only a particular type of data may be entered into the database or that only a particular sort of
operation can be performed on the data inside.
Data Accuracy − Data accuracy is guaranteed by constraints, which make sure that only true
data is entered into a database. For example, a limitation may stop a user from entering a
negative value into a field that only accepts positive numbers.
Data Consistency − The consistency of data in a database can be upheld by using constraints.
These constraints are able to ensure that the primary key value in one table is followed by the
foreign key value in another table.
Data integrity − The accuracy and completeness of the data in a database are ensured by
constraints. For example, a constraint can stop a user from putting a null value into a field that
requires one.
Domain Constraints In DBMS
➢ In DBMS table is viewed as a combination of rows and columns
➢ For example, if you are having a column called month and you want only (jan,
feb, march……) as values allowed to be entered for that particular column which is referred
to as domain for that particular column
Definition: Domain constraint ensures two things it makes sure that the data value entered for that
particular column matches with the data type defined by that column.
It shows that the constraints (NOT NULL/UNIQUE/PRIMARY KEY/FOREIGN
KEY/CHECK/DEFAULT)
➢ Constraints are nothing but the rules that are to be followed while entering data into
columns of the database table.
➢ Constraints ensure that the data entered by the user into columns must be within the
criteriaspecified by the condition.
➢ We have 6 types of key constraints in DBMS
1. Not Null
2. Unique
3. Default
4. Check
5. Primary key
6. Foreign key
15
1. Not Null:
• Null represents a record where data may be missing data or data for that record may
be optional.
• Once not null is applied to a particular column, you cannot enter null values to that
column.
• A not null constraint cannot be applied at table level.
Example:
Create table EMPLOYEE (id int Not null, name varchar Not null, Age int not null,
address char (25), salary decimal (18,2), primary key(id));
➢ In the above example we have applied not null on three columns id, name and age
which means whenever a record is entered using insert statement all three columns
should contain a value other than null.
➢ We have two other columns address and salary, where not null is not applied
which means that you can leave the row as empty.
2. Unique:
Some times we need to maintain only. Unique data in the column of a database table,
this is possible by using a Unique constraint.
Example:
16
Create table PERSONS (id int unique, last_name varchar (25) not null, First name
varchar (25), age int);
not supposed to enter the data that is already present, simply no two ID values are
same.
3. Default:
➢ When a column is specified as default with same value then all the rows will use the
same value i.e., each and every time while entering the data we need not enter that
value.
➢ But default column value can be customised i.e., it can be over ridden when inserting
a data for that row based on the requirement.
(Row with default values “abc”)
Example:
Create table EMPLOYEE (id int Not null, last_name varchar (25) Not null, first_name
varchar (25), Age int, city varchar (25) Default Hyderabad);
17
➢ As a result, whenever you insert a new row each time you need not enter a value
for this default column that is entering a column value for a default column is optional.
4. Check:
➢ Check constraint ensures that the data entered by the user for that column is within the
range of values or possible values specified.
Example: Create table STUDENT (id int, name varchar (25), age int, check(age>=18));
➢ As we have used a check constraint as (age>=18) which means value entered by user
for this age column while inserting the data must be less than or equal to 18.
5. Primary Key:
➢ A primary key is a constraint in a table which uniquely identifies each row record
in a database table by enabling one or more column in the table as primarykey.
6. Foreign Key:
➢ The foreign key constraint is a column or list of columns which points to the
primary key column of another table.
➢ The main purpose of the foreign key is only those values are allowed in the present
table that will match to the primary key column of another table.
From the above two tables, COURSE_ID is a primary key of the table
STUDENT_MARKS and also behaves as a foreign key as it is same in
STUDENT_DETAILS and STUDENT_MARKS.
Example:
(Reference Table)
Create table CUSTOMER1 (id int, name varchar (25), course varchar (10), primary key
(ID));
(Child table)
19
Entity Integrity constraints:
➢ These constraints are used to ensure the uniqueness of each record or row inthe data table.
➢ Entity Integrity constraints says that no primary key can take NULL VALUE, since using
primary key we identify each tuple uniquely in arelation.
Example:
Explanation:
➢ In the above relation, EID is made primary key, and the primary key can‟t take NULL values but
in the 3rd tuple, the primary key is NULL, so it is violating Entity integrity constraints.
➢ The referential integrity constraint is specified between two relations or tables and used to
maintain the consistency among the tuples in two relations.
➢ This constraint is enforced through foreign key, when an attribute in the foreign key of relation
R1 have the same domain as primary key of relation R2, then the foreign key of R1 is said
to reference or refer to the primary key of relation R2.
➢ The values of the foreign key in a tuple of relation R1 can either take the values of the primary
key for some tuple in Relation R2, or can take NULL values, butcan‟t be empty.
20
Explanation:
➢ In the above, DNO of the first relation is the foreign key and DNO in the second relation
is the primary key
➢ DNO=22 in the foreign key of the first relation is not available in the second relation so, since
DNO=22 is not defined in the primary key of the second relation therefore Referential
integrity constraints is violated here.
ER Model, when conceptualized into diagrams, gives a good overview of entity-relationship, which is
easier to understand. ER diagrams can be mapped to relational schema, that is, it is possible to create
relational schema using ER diagram. We cannot import all the ER constraints into relational model, but
an approximate schema can be generated.
There are several processes and algorithms available to convert ER Diagrams into Relational Schema.
Some of them are automated and some of them are manual. We may focus here on the mapping diagram
contents to relational basics.
Mapping Entity
Mapping Relationship
21
Mapping Process
• Create table for a relationship.
• Add the primary keys of all participating Entities as fields of table with their respective data
types.
• If relationship has any attribute, add each attribute as field of table.
• Declare a primary key composing all the primary keys of participating entities.
• Declare all foreign key constraints.
A weak entity set is one which does not have any primary key associated with it.
Mapping Process
• Create table for weak entity set.
• Add all its attributes to table as field.
• Add the primary key of identifying entity set.
• Declare all foreign key constraints.
22
Mapping Process
• Create tables for all higher-level entities.
• Create tables for lower-level entities.
• Add primary keys of higher-level entities in the table of lower-level entities.
• In lower-level tables, add all other attributes of lower-level entities.
• Declare primary key of higher-level table and the primary key for lower-level table.
• Declare foreign key constraints.
Views
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Advantages of View:
1. Complexity: Views help to reduce the complexity. Different views can be created on the same
base table for different users.
2. Security: It increases the security by excluding the sensitive information from the view.
3. Query Simplicity: It helps to simplify commands from the user. A view can draw data from
several different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure of the database.
Views can be used to rename the columns without affecting the base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can automatically
check the data to ensure that it meets the specified integrity constraints.
6. Storage Capacity: Views take very little space to store the data.
7. Logical Data Independence: View can make the application and database tables to a certain
extent independent.
23
Disadvantages of View:
The DML statements which can be performed on a view created using single base table have certain
restrictions are:
1. You cannot INSERT if the base table has any not null column that do not appear in view.
2. You cannot INSERT or UPDATE if any of the column referenced in the INSERT or UPDATE
contains group functions or columns defined by expression.
3. You can't execute INSERT, UPDATE, DELETE statements on a view if with read only option is
enabled.
4. You can't be created view on temporary tables.
5. You cannot INSERT, UPDATE, DELETE if the view contains group functions GROUP BY,
DISTINCT or a reference to a psuedocolumn rownum.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or
multiple tables.
24
Syntax:
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables in the SELECT statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
25
NAME ADDRESS MARKS
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
26
Relational Algebra
SELECT: Select operation chooses the subset of tuples from the relation that satisfies the
given condition mentioned in the syntax of selection. The selection operation is also known
as horizontal partitioning since it partitions the table or relation horizontally.
Notation:
σ c(R)
where ‘c’ is selection condition which is a boolean expression(condition), we can have a
single condition like Roll= 3 or combination of condition like X>2 AND Y<1, symbol
‘σ (sigma)’ is used to denote select(choose) operator.
Roll Name Department Fees Team
1 Bikash CSE 22000 A
2 Josh CSE 34000 A
3 Kevin ECE 36000 C
4 Ben ECE 56000 D
Select all the student of Team A : σ Team = 'A' (Student)
Roll Name Department Fees Team
1 Bikash CSE 22000 A
2 Josh CSE 34000 A
PROJECT:It displays the specific column of a table. It is denoted by pie (∏). It is a vertical
subset of the original relation. It eliminates duplicate tuples.
Syntax
The syntax is as follows − πA1,A2,A3,...,Ak(r)
Set Operations
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both the
tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
SELECT column_name FROM table1 UNION ALL SELECT column_name FROM table2;
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
Rename operation
Syntax
ρ newname ( tablename or expression)
Example 1
The student table is renamed with newstudent with the help of the following command −
ρnewstudent (student)
Example 2
The name, branch column of student table are renamed and newbranch respectively
Joins
SQL JOIN clause is used to query and access data from multiple tables by establishing logical
relationships between them. It can access data from multiple tables simultaneously using
common key values shared across different tables.
We can use SQL JOIN with multiple tables. It can also be paired with other clauses, the most
popular use will be using JOIN with WHERE clause to filter data retrieval.
name course_name
Alice Math
Alice Science
Alice History
Alice Art
Bob Math
Bob Science
Bob History
Bob Art
Carol Math
Carol Science
Carol History
Carol Art
Dave Math
Dave Science
Dave History
Dave Art
Self Join
A self JOIN is a regular join, but the table is joined with itself.
Syntax:
select column_name(s) from table1 t1, table1 t2 where condition;
Example
SELECT s1.name AS student1, s2.name AS student2, s1.course_id
FROM students s1
INNER JOIN students s2 ON s1.course_id = s2.course_id
WHERE s1.student_id < s2.student_id;
In this query:
Result:
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables
Syntax:
select column_name(s) from table1 inner join table2
on table1.column_name = table2.column_name;
Example:
SELECT students.name, courses.course_name FROM students
INNER JOIN courses ON students.course_id = courses.course_id;
Result:
name course_name
Alice Math
Bob Science
Carol History
OUTER JOIN
In a relational DBMS, we follow the principles of normalization that allows us to minimize the
large tables into small tables. By using a select statement in Joins, we can retrieve the big table
back. Outer joins are of following three types.
1. Left outer join
2. Right outer join
3. Full outer join
Syntax:
Result:
name course_name
Alice Math
Bob Science
Carol History
Dave NULL
Returns all records from the right table and the matched records from the left table. If no match,
NULL values are returned for columns from the left table.
Syntax:
Example
name course_name
Alice Math
Bob Science
Carol History
NULL Art
name course_name
Alice Math
Bob Science
Carol History
Dave NULL
NULL Art
Division
Notation: R(X,Y)/S(Y)
X and Y are the attributes/columns present in relation. We can have multiple attributes in
relation, but keep in mind that attributes of S must be a proper subset of attributes of R.
Let's have two relations, ENROLLED and COURSE. ENROLLED consist of two attributes
STUDENT_ID and COURSE_ID. It denotes the map of students who are enrolled in given
courses.
ENROLLED
STUDENT_ID COURSE_ID
Student_1 DBMS
Student_2 DBMS
Student_1 OS
Student_3 OS
COURSE
COURSE_ID
DBMS
OS
Now the query is to return the STUDENT_ID of students who are enrolled in every course.
SQL>ENROLLED(STUDENT_ID, COURSE_ID)/COURSE(COURSE_ID)
Output:
STUDENT_ID
Student_1
In Tuple Relational Calculus, a query is expressed as a set of tuples. A tuple variable represents a
row (or a record) in the table, and the conditions specified in the query refer to the attributes
(columns) of that tuple. The basic syntax follows this form:
{T | condition(T)}
Where:
T is a tuple variable.
Let's write a TRC query to find the names of employees who are older than 30:
Here:
T.Age > 30 is the condition specifying that we only want employees whose age is greater
than 30.
This query reads: "Find all names of employees (T.Name) such that there exists a tuple T in the
Employee table where T.Age > 30."
In Domain Relational Calculus, the query is expressed in terms of the values (or domains) of
attributes, rather than tuples. A domain variable represents a value in a specific domain (like a
column value), and the conditions refer to these domain variables.
Where:
D1, D2, ..., Dn are domain variables representing the values of different columns.
condition(D1, D2, ..., Dn) is the condition that the domain variables must satisfy.
Here:
E.Age > 30 is the condition that the employee’s age must be greater than 30.
E.Name = D states that we want the name of the employee, represented by the domain
variable D.
This query reads: "Find all values D (names) such that there exists a tuple E in the Employee
table where E.Age > 30 and E.Name = D."
o Query specifies conditions on the values of attributes rather than on entire tuples.
Relational Calculus is a theoretical query language, primarily used for specifying what
we want from the database, without specifying how to retrieve it.
For instance, the SQL equivalent of the above queries could be:
SQL Equivalent for TRC Example:
SELECT Name
FROM Employee
SELECT Name
FROM Employee
In SQL, the query specifies both the what (which column, Name, to retrieve) and the how (using
SELECT and WHERE clauses). While relational calculus is focused on expressing conditions
and results, SQL tells the DBMS how to execute the query to get the result.
Summary
There are two forms: Tuple Relational Calculus (TRC) and Domain Relational Calculus
(DRC).
TRC uses tuples (whole rows) as variables, while DRC uses domain variables (individual
attribute values).
Relational calculus queries are more abstract, while SQL is more procedural and
optimized for practical use in databases.