0% found this document useful (0 votes)
60 views39 pages

DBMS Unit2 Cser22

dbms notes

Uploaded by

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

DBMS Unit2 Cser22

dbms notes

Uploaded by

saipranith235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT-2

TOPICS

Introduction to the Relational Model:

● Integrity constraint over relations


● enforcing integrity constraints
● querying relational data
● logical data base design
● introduction to views, destroying/altering tables and views.
● Relational Algebra
● Tuple relational Calculus, Domain relational calculus.
What is the Relational Model?

E.F. Codd proposed the relational Model to model data in the form of relations or tables. After
designing the conceptual model of the Database using ER diagram, we need to convert the
conceptual model into a relational model which can be implemented using any
RDBMS language like Oracle SQL, MySQL, etc. So we will see what the Relational Model is.

The relational model for database management is an approach to logically represent and
manage the data stored in a database. In this model, the data is organized into a collection of
two-dimensional inter-related tables, also known as relations. Each relation is a collection
of columns and rows, where the column represents the attributes of an entity and the rows (or
tuples) represents the records.

The use of tables to store the data provided a straightforward, efficient, and flexible way to store
and access structured information. Because of this simplicity, this data model provides easy
data sorting and data access. Hence, it is used widely around the world for data storage and
processing.

Let's look at a scenario to understand the relational model:

Consider a case where you wish to store the name, the CGPA attained, and the roll number of
all the students of a particular class. This structured data can be easily stored in a table as
described below:

As we can notice from the above relation:

1. Any given row of the relation indicates a student i.e., the row of the table describes a real-world
entity.
2. The columns of the table indicate the attributes related to the entity. In this case, the roll
number, CGPA, and the name of the student.
NOTE: A database implemented and organized in terms of the relational model is known as a
relational database management system (RDBMS). Hence, the relational model describes how
data is stored in relational databases.

Advantages of the Relational Model


● Simple model: Relational Model is simple and easy to use in comparison to other
languages.
● Flexible: Relational Model is more flexible than any other relational model present.
● Secure: Relational Model is more secure than any other relational model.
● Data Accuracy: Data is more accurate in the relational data model.
● Data Integrity: The integrity of the data is maintained in the relational model.
● Operations can be Applied Easily: It is better to perform operations in the relational
model.

Disadvantages of the Relational Model


● Relational Database Model is not very good for large databases.
● Sometimes, it becomes difficult to find the relation between tables.
● Because of the complex structure, the response time for queries is high.

Characteristics of the Relational Model


● Data is represented in rows and columns called relations.
● Data is stored in tables having relationships between them called the Relational model.
● The relational model supports the operations like Data definition, Data manipulation,
and Transaction management.
● Each column has a distinct name and they are representing attributes.
● Each row represents a single entity.
Integrity Constraints
(OR) Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have
to be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.

Types of Integrity Constraint:

1. Domain constraints:
each table has certain set of columns and each column allows a same type of data,
based on its data type. The column does not accept values of any other data
type.
Domain constraints are user defined data type and we can define them like this:

Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY
/ FOREIGN KEY / CHECK / DEFAULT)

Example:

Example:

CREATE TABLE Student (

std_name VARCHAR(50) NOT NULL,

std_rollno INT PRIMARY KEY,

std_mobileno INT UNIQUE,

std_age INT CHECK (std_age > 18 AND std_age < 25),

std_city VARCHAR(50) DEFAULT 'hyderabad'

);

The table "Student" now has the following columns:

`std_name`: Stores the name of the student as a non-null value.

`std_rollno`: Serves as the primary key, ensuring each student has a unique roll
number and null values are not allowed.

`std_mobileno`: Contains the mobile number of the student, ensuring uniqueness


among students.

`std_age`: Validates that the student's age falls within the range of 19 to 24 years
(inclusive).

`std_city`: Represents the city of the student, with a default value of 'hyderabad' if not
specified.

Advantages of Domain Constraints:


Data Integrity: Domain constraints ensure that the data stored in a column follows the
specified data type and range. This helps maintain the accuracy and reliability of the data
by preventing incorrect or inconsistent values from being entered.

Data Validation: Domain constraints provide a way to validate data at the column level.
They ensure that only valid and acceptable values are entered into the database, helping
to enforce business rules and prevent data entry errors.

2. Key constraints:
There are three primary types of key constraints commonly used in database
management systems (DBMS): primary key, unique key, and foreign key constraints.
Let's explore each type with examples:
a) Primary Key Constraint:
Primary key uniquely identifies each record in a table. It must have unique values and
cannot contain nulls. In the below example the student_id field is marked as primary key,
that means the student_id field cannot have duplicate and null values.
Example:
CREATE TABLE Students (
student_id INT PRIMARY
KEY, student_name
VARCHAR(50), student_email
VARCHAR(100)
);

In the example above, the `student_id` column is defined as the primary key for the
`Students` table. It guarantees the uniqueness of each `student_id` value, allowing us to
identify each student uniquely.
b) Foreign key Constraint:
Foreign keys are the columns of a table that points to the primary key of another table.
They act as a cross-reference between tables.

Example:

CREATE TABLE cse_student (

cse_student_id INT PRIMARY KEY,

cse_student_name VARCHAR(50),

FOREIGN KEY (cse_student_id) REFERENCES Students(student_id)

);

c) Unique Key Constraint:


A unique key constraint ensures that the values in a specific column or a combination of
columns are unique across all rows in a table. It allows for the insertion of NULL values
but restricts the duplication of non-NULL values. Here's an example:
CREATE TABLE Employees
( employee_id INT,
employee_email VARCHAR(100)
UNIQUE, employee_phone VARCHAR(15)
UNIQUE
);
In the example above, both `employee_email` and `employee_phone` columns have
unique key constraints applied to them. It guarantees that each email and phone number
in the table will be unique.
Advantages of Key Constraints:

Uniqueness: Key constraints, such as primary keys and unique keys, enforce the
uniqueness of values within a column or a combination of columns. This ensures that each
record in the table can be uniquely identified, preventing duplicate entries and maintaining
data integrity.

Relationship Establishment: Key constraints, especially foreign keys, establish


relationships between tables. By linking the values in one table to the primary key values
in another table, key constraints enable the creation of meaningful relationships. This
facilitates data retrieval, manipulation, and the maintenance of referential integrity.

3. Entity integrity constraints:


o The entity integrity constraint states that primary key value can't be null.
o 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.
o A table can contain a null value other than the primary key field.

Example:

Advantages of Entity Integrity Constraints:

Uniqueness and Identification: Entity integrity constraints, typically enforced through


primary key constraints, ensure that each row in a table has a unique identifier. This
guarantees reliable identification and retrieval of individual records, making it easier to work
with the data.

Data Consistency: Entity integrity constraints prevent NULL values in the primary key
column, ensuring that every row in the table has a valid and non-null identifier. This
maintains data consistency and helps avoid data anomalies that can arise from missing or
incomplete identifiers.

4. Referential Integrity Constraints:


o A referential integrity constraint is specified between two tables.
o 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.

Example:

Advantages of Referential Integrity Constraints:

Relationship Maintenance: Referential integrity constraints, established through foreign


key constraints, help maintain relationships between tables. They ensure that the values
in the foreign key column(s) in one table correspond to the values in the referenced primary
key column(s) of another table. This ensures the integrity and consistency of data across
related tables.

Data Accuracy: Referential integrity constraints prevent orphaned or inconsistent data by


enforcing the existence of related records in the referenced table. They ensure that only
valid and existing references are made, improving data accuracy and preventing data
inconsistencies.
Logical database Design : ER Diagram to Table Conversion
1. Strong Entity set with Simple attributes
The Strong Entity set becomes the table and the attributes of the Entity set becomes the
table attributes. The key attribute of the entity set becomes the primary key of the table.

Let’s take an example: Here we have an entity set Employee with the attributes Name,
Age, Emp_Id and Salary. When we convert this ER diagram to table, the entity set becomes
table so we have a table named “Employee” as shown in the following diagram. The
attributes of the entity set becomes the attributes of the table.

2. Strong Entity Set With Composite Attributes


Now we will see how to convert Strong entity set with composite attributes ER to table. The
conversion is fairly simple in this case as well. The entity set will be the table and the simple
attributes of the composite attributes will become the attributes of the table while the
composite attribute itself will be ignored during conversion.

Let’s take an example. As you can see we have a composite attribute Name and this
composite attribute has two simple attributes First_N and Last_N. While converting this ER
to table we have not used the composite attribute itself in the table instead we have used
the simple attributes of this composite attribute as table’s attributes.
3. Relationship Set to Table conversion
While converting the relationship set to a table, the primary attributes of the two entity sets
becomes the table attributes and if the relationship set has any attribute that also becomes
the attribute of the table.

In the following example, we have two entity sets Employee and Department. These entity
sets are associated to each other using the Works relationship set. To convert this
relationship set Works to the table, we take the primary attributes of each entity set, these
are Emp_Id and Dept_Id and all the attributes of the relationship set and form a table.
QUERYING
RELATIONAL DATA
In the relational model, querying refers to the process of retrieving specific data from a
database. It allows you to ask questions or make requests to the database and get the
desired information in return. Queries are written using a structured language called SQL
(Structured Query Language).

Syntax:

SELECT column1, column2 FROM table WHERE condition;

Example:

Let's assume the "student" table has the following structure and contains 7 records:
2. SELECT name, rollno FROM students;

3. SELECT * FROM students WHERE rollno = 21;

Output: No records returned as there is no student with roll number 21.


4. SELECT * FROM students WHERE age > 12 AND age < 29;

7. SELECT * FROM students WHERE age IN (20, 21, 22);

8. SELECT * FROM students WHERE age BETWEEN 12 AND 29;


Order by and filter by clauses:
1. ORDER BY:

The "ORDER BY" clause is used to sort the result set of a query in a specified order. It
allows you to arrange the retrieved rows in ascending (default) or descending order based
on one or more columns.

Syntax:

SELECT column1, column2, ...

FROM table

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

● "column1, column2, ..." represents the columns you want to retrieve from the table.
● "table" refers to the name of the table from which you want to retrieve the data.
● "column1 [ASC|DESC], column2 [ASC|DESC], ..." specifies the columns by which you
want to sort the result set. You can add "ASC" for ascending order (default) or "DESC" for
descending order after each column.

2. WHERE:
The "WHERE" clause is used to filter the result set based on specific conditions. It allows
you to retrieve only the rows that satisfy the given condition(s).

Syntax:
SELECT column1, column2, ...
FROM table
WHERE condition;
▪ "column1, column2, ..." represents the columns you want to retrieve from the table.
▪ "table" refers to the name of the table from which you want to retrieve the data.
▪ "condition" specifies the filtering condition(s) that the rows must meet. For
example, "column_name = value" or "column_name > value".

By using the "ORDER BY" clause, you can control the order in which the rows are
displayed in the result set. The "WHERE" clause allows you to filter the rows based
on specific conditions, so only the relevant data is retrieved.

These clauses are commonly used together in SQL queries to retrieve, sort, and filter
data from a database table.
Types of keys:

Types of Keys
E Keys play an important role in the relational database.
F 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.

For example, ID is used as a key in the Student table because it is unique for each student.
In the PERSON table, passport_number, license_number, SSN are keys since they are
unique for each person.
1. Primary key
o 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.
o 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.
o For each entity, the primary key selection is based on requirements and developers.

2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple(
here values may or may not be null ).
o Except for the primary key, the remaining attributes are considered a candidate key.
The candidate keys are as strong as the primary key.

For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of
the attributes, like SSN, Passport_Number, License_Number, etc., are considered a
candidate key.
3. Super Key

Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of
a candidate key.

For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME),


the name of two employees can be the same, but their EMPLYEE_ID can't be the same.
Hence, this combination can also be a key.

4. Foreign key
o Foreign keys are the column of the table used to point to the primary key of another
table.
o Every employee works in a specific department in a company, and employee and
department are two different entities. So we can't store the department's information
in the employee table. That's why we link these two tables through the primary key
of one table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a new
attribute in the EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.

5. 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. In other words, the total
number of the alternate keys is the total number of candidate keys minus the primary key.
The alternate key may or may not exist. If there is only one candidate key in a relation, it
does not have an alternate key.

For example, employee relation has two attributes, Employee_Id and PAN_No, that act
as candidate keys. In this relation, Employee_Id is chosen as the primary key, so the other
candidate key, PAN_No, acts as the Alternate key.

Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a
real table 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 act as a proxy or virtual table created from the original table. Views simplify SQL
queries and allow secure access to underlying tables. Views in DBMS can be visualized
as virtual tables that are formed by original tables from the database.
6. 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.

For example, in employee relations, we assume that an employee may be assigned


multiple roles, and an employee may work on multiple projects simultaneously. So the
primary key will be composed of all three attributes, namely Emp_ID, Emp_role, and
Proj_ID in combination. So these attributes act as a composite key since the primary key
comprises more than one attribute.

Views in SQL
Sample Table
For creating a view (simple and complex views), and updating and deleting the views we
will take some sample data and tables that store the data.

Let's take an employee table that stores data of employees in a particular company:

Employee Table:

This table contains details of employees in a particular company and has data fields such
as EmpID, EmpName, Address, Contact. We have added 6 records of employees for our
purpose.

EmpID EmpName Address Contact

1 Alex London 05-12421969

2 Adolf San Francisco 01-12584365

3 Aryan Delhi 91-9672367287

4 Bhuvan Hyderabad 91-9983288383

5 Carol New York 01-18928992

6 Steve California 01-13783282

EmpRole Table:

This table contains details of employees' roles in a particular company and has data fields
as EmpID, Role, Dept. We have stored all the records particular to the EmpID of each
employee.

EmpID Role Dept

1 Intern Engineering

2 Trainee IT

3 Executive HR

4 SDE-1 Engineering

5 SDE-2 Engineering

6 Technical Architect Engineering

1. Creating View in DBMS:


The view can be created by using the CREATE VIEW statement, Views can be simple or
complex depending on their usage.

Syntax:

CREATE VIEW veiwName AS


SELECT column1, column2,....
FROM tableName
WHERE condition;

Here, viewName is the Name for the View we set, tableName is the Name of the table and
condition is the Condition by which we select rows.

Creating a Simple View (Creating View from a single table )

Simple view is the view that is made from a single table, It takes only one table and just
the conditions, It also does not take any inbuilt SQL functions like
AVG(), MIN(), MAX() etc, or GROUP BY clause.

While creating a simple view, we are not creating an actual table, we are just projecting the
data from the original table to create a view table.

Let's look at some examples for creating a simple view.

Example 1: In this example, we are creating a view table from Employee Table for getting
the EmpID and EmpName. So the query will be:

CREATE VIEW EmpView1 AS


SELECT EmpID, EmpName
FROM Employee;

Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.

SELECT * from EmpView1;

Output:

The view table EmpView1 that we have created from Employee Table contains EmpID and
EmpName as its data fields.

EmpID EmpName

1 Alex

2 Adolf

3 Aryan

4 Bhuvan
EmpID EmpName

5 Carol

6 Steve

Example 2: In this example, we are creating a view table from EmpRole Table for getting
the EmpID and Dept for employees having EmpIDs less than 4. So the query will be:

CREATE VIEW EmpView2 AS


SELECT EmpID, Dept
FROM EmpRole
WHERE EmpID<4;

Now to see the data in the EmpView2 view created by us, We have to simply use the
SELECT statement.

SELECT * from EmpView2;

Output:

The view table EmpView2 that we have created from EmpRole Table
contains EmpID and Dept as its data fields.

EmpID Dept

1 Engineering

2 IT

3 HR

Creating a Complex View(Creating View from multiple tables):

The complex view is the view that is made from multiple tables, It takes multiple tables in
which data is accessed using joins or cross products, It contains inbuilt SQL functions like
AVG(), MIN(), MAX() etc, or GROUP BY clause. So, whenever we need to access data
from multiple tables we can make use of Complex Views.

Let's look at some examples for creating the complex view.

Example:

In this example, we are creating a view table using Employee Table and EmpDept table
for getting the EmpName from the Employee table and Dept from EmpDept. So the query
will be:

CREATE VIEW CompView AS


SELECT Employee.EmpName, EmpRole.Dept
FROM Employee, EmpRole
WHERE Employee.EmpID = EmpRole.EmpID;

Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.

SELECT * from CompView;

Output:

The view table CompView that we have created from Employee Table and
EmpRole Table contains EmpName and Dept as its data fields. We have used the cross-
join to get our necessary data.

EmpName Dept

Alex Engineering

Adolf IT

Aryan HR

Bhuvan Engineering

Carol Engineering

Steve Engineering

2. Deleting View in DBMS:


Now we know how to create simple and complex views but what if we don't need our
created views anymore, So we need to delete the view so as we DROP a table in SQL,
similarly, we can delete or drop a view using the DROP statement.

The DROP statement completely deletes the structure of the view.

Syntax:

DROP VIEW ViewName;

Here ViewName is the name of the view to be deleted.

Example:

Let's delete one of our created views, say EmpView1.

DROP VIEW EmpView1;

Let's use the SELECT statement on Deleted View.


SELECT * from EmpView1;

Output:

Now SQL Editor will give us an error saying the table does not exist as the table is now been
deleted.

ORA-00942: table or view does not exist

3. Updating View in DBMS:


Suppose we want to add more columns to the created view so we will have to update the
view.

For updating the views we can use CREATE OR REPLACE VIEW statement, new
columns will replace or get added to the view.

Syntax:

CREATE OR REPLACE VIEW ViewName AS


SELECT column1,coulmn2,..
FROM TableName
WHERE condition;

For Updating a view CREATE OR REPLACE statement is used. Here, viewName is the
Name of the view we want to update, tableName is the Name of the table and
condition is the Condition by which we select rows.

Example:

let's take the above created simple view EmpView1 and we want to one more column of
address to our EmpView1 from Employee Table.

CREATE OR REPLACE VIEW EmpView1 AS


SELECT EmpID, EmpName, Address
FROM Employee;

Now to see the data in the EmpView1 view created by us, We have to simply use the
SELECT statement.

SELECT * from EmpView1;

Output:

The data fields of view table EmpView1 have been updated to EmpID, EmpName, and
Address.

EmpID EmpName Address

1 Alex London
EmpID EmpName Address

2 Adolf San Francisco

3 Aryan Delhi

4 Bhuvan Hyderabad

5 Carol New York

6 Steve California
UNIT-2
IMPORTANT QUESTIONS
1. Explain Relational Model.
2. Database languages( DDL, DML, DQL, TCL, DCL)
3. Integrity Constraints ( Entity integrity constraints, Referential Integrity Constraints,
Key constraints, Domain Constraints ).
4. Various Types of Keys ( primary key , foreign key, super key, candidate
key, alternate key, composite key ).
5. Inclusion dependence.
6. Querying in relational data ( hint : using select command)
7. Logical database design ( converting ER diagrams to tables with and without key
constraints).
8. Views? Creating views from single and multiple tables, updating and
deleting views?
9. How to Drop tables and views using sql?
10. What is relational algebra and what are its properties?
11. Fundamental operations in relational algebra and explain with examples?
(selection, projection, Cartesian product, set operations, join operations)
12. What is relational calculus ? explain tuple relational calculus and domain relational
calculus with an examples?

You might also like