0% found this document useful (0 votes)
47 views

DBMS Unit 1 Notes Full

The document discusses database design using the Entity-Relationship (ER) model. It begins by introducing ER modeling and its use in conceptual database design. It then describes the six main steps of database design: 1) requirements analysis, 2) conceptual design using ER modeling, 3) logical design by converting the ER schema to a relational schema, 4) schema refinement, 5) physical design, and 6) application and security design. The document focuses on entities, attributes, relationships, and how they are modeled in ER diagrams including examples like employees, departments, and the works_in relationship. It also covers relationship sets, instances, and key constraints.

Uploaded by

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

DBMS Unit 1 Notes Full

The document discusses database design using the Entity-Relationship (ER) model. It begins by introducing ER modeling and its use in conceptual database design. It then describes the six main steps of database design: 1) requirements analysis, 2) conceptual design using ER modeling, 3) logical design by converting the ER schema to a relational schema, 4) schema refinement, 5) physical design, and 6) application and security design. The document focuses on entities, attributes, relationships, and how they are modeled in ER diagrams including examples like employees, departments, and the works_in relationship. It also covers relationship sets, instances, and key constraints.

Uploaded by

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

INTRODUCTION TO DATABASE DESIGN

The Entity-Relation data model allows us to describe the data involved in a real-
world enterprise in terms of objects and their relationships and is widely used to
(levelop an initial databa.'3e design. It provides useful concepts that allow us to
move from an informal description of what users want 1'rorn their database to a
more detailed, precise description that can be implemented in a DBMS.

DATABASE DESIGN AND ER DIAGRAMS

The database design process can be divided into six steps. The ER model is most
relevant to the first three steps.

1. Requirements Analysis:

The very first step in designing a database application is to understand


what data is to be stored in the database,what applications must be built
on top of it, and what operations are most frequent and subject to
performance requirements.

In other words, we must find out what the users want from the
database. This is usually an informal process that involves discussions with
user groups.

Several methodologies have been proposed for organizing and presenting the
information gathered in this step, and some automated tools have been
developed to support this process.

2. Conceptual Database Design:

The information gathered in the requirements analysis step is used to


develop a high-level description of the data to be stored in the database,
along with the constraints known to hold over this data. This step is often
carried out using the ER model .

The ER model is one of several high-level, or semantic, data models


used in database design. The goal is to create a simple description of the
data that closely matches how users and developers think of the data (and
the people and processes to be represented in the data).

3. Logical Database Design:

We must choose a DBMS to implement our database design, and convert


the conceptual database design into a database schema in the data model
of the chosen DBMS. We will consider only relational DBMSs, and
therefore, the task in the logical design step is to convert an ER schema into
a relational database schema.

4. Schema Refinement:

The fourth step ill databa')e design is to analyze the collection of relations
in our relational database schema to identify potential problems, and to
refine it.

schema refinement can be guided by some elegant and powerful theory.

5. Physical Database Design:

In this step, we consider typical expected workloads that our


database must support and further refine the database design to ensure
that it meets desired performance criteria. This step may simply involve
building indexes on some tables and clustering some tables, or it may
involve a substantial redesign of parts of the database schema obtained
from the earlier design steps

6. Application and Security Design:

Any software project that involves a DBMS must consider aspects of the
application that go beyond the database itself. Design methodologies like
UML try to address the complete software design and development cycle.

Briefly, we must identify the entities (e.g., users, user groups, departments)
and processes involved in the application. We must describe the role of
each entity in every process that is reflected in some application task, as
part of a complete workflow for that task.

ENTITIES, ATTRIBUTES, AND ENTITY SETS

An entity is an object in the real world that is distinguishable from other


objects

For example Each person is an entity . and bank accounts is considered as


entities.

It is often useful to identify a collection of similar entities. Such a collection


is called an entity set.

Note that entity sets need not be disjoint; the collection of toy department
employees and the collection of appliance department employees may both
contain employee John (who happens to work in both departments).

An entity is described using a set of attributes. All entities in a given entity set
have the same attributes.

For example, the Employees entity set could use name, social security number
(ssn), and parking lot (lot) as attributes. In this case we will store the name, social
security number, and lot number for each employee. However, we will not store,
say, an employee's address (or gender or age).

The Employees entity set with attributes ssn, name, and lot is shown in Figure 2.1.
An entity set is represented by a rectangle, and an attribute is represented by an
oval.
RELATIONSHIP AND RELATIONSHIP SETS

A relationship is an association among two or more entities. For example, we may


have the relationship that RAM works in the CSE department.we may wish to
collect a set of similar relationships into a relationship set. A relationship set can
be thought of as a set of n-tuples.

Each n-tuple denotes a relationship involving n entities el through en, where


entity ei is in entity set Ei . In Figure 2.2 we show the relationship set Works_In,

in which each relationship indicates a department in which an employee works.

Descriptive attributes.
THE WORKS-IN RELATIONSHIP SET

A relationship can also have descriptive attributes. Descriptive attributes are used
to record information about the relationship, rather than about any one of the
participating entities;

for example, we may wish to record that RAM works in the CSE department as of
January 1991.
This information is captured in Figure by adding an attribute, since, to Works_In.

A relationship must be uniquely identified by the participating entities, without


reference to the descriptive attributes.

In the Works_In relationship set, for example, each Works_In relationship must
be uniquely identified by the combination of employee ssn and department dId.
Thus, for a given employee-department pair, we cannot have more than one
associated since value.

2 Instance
EMPLOYEES WORKS_IN
DEPARTMENTS
Total participation Many to Many
Total participation

An Instance of the Works_In Relationship Set

An instance of a relationship set is a set of relationships. Intuitively, an instance


can be thought of as a 'snapshot' of the relationship set at some instant in time.
An instance of the vVorks.ln relationship set is shown in Figure .
Each Employees entity is denoted by its ssn, and each Departments entity is
denoted by its did, for simplicity. The since value is shown beside each
relationship. (The 'many-te-many' and 'total participation' comments in the figure
are discussed later, when we discuss integrity constraints.)

Ternary Relationship :

As another example of an ER diagram, suppose that each department has offices


in several locations and we want to record the locations at which each employee
works.
This relationship is ternary because we must record an association between an
employee, a department, and a location.
The ER diagram for this variant of Works_In, which we call Works.ln2, is shown in
Figure

A Ternary Relationship Set

Reports_To Relationship

The entity sets that participate in a relationship set need not be distinct;
sometimes a relationship might involve two entities in the same entity set. For
example, consider the Reports_To relationship set shown in Figure
Since employees report. to other employees, every relationship in Reports_To is
of the form (emlJ1. emp2) , where both empl and empz are entities in Employees.

However, they play different roles: ernpl reports to the managing employee
emp2, which is reflected in the role indicators supervisor and subordinate in
Figure.
If an entity set plays more than one role, the role indicator concatenated with an
attribute name from the entity set gives us a unique name for each attribute in
the relationship set. For example, the Reports_To relationship
set has attributes corresponding to the ssn of the supervisor and the ssn of the
subordinate, and the names of these attributes are supcrvisoLssn and
subordinate-ssn.

The Reports_To Relationship Set

ADDITIONAL FEATURES OF THE ER MODEL

1. Key Constraints

constraint is a condition specified on the data.


OR
Constraint is a condition applied to the column in table to store the data item
uniquely.

Consider the Works-.In relationship shown in Figure.


An employee can work in several departments, and a department can have
several employees, &.,illustrated in the works_In instance shown in Figure 2.3.
Employee 231-31-5368 h&., worked in Department 51 since 3/3/93 and in
Department 56 since 2/2/92. Department 51 has two employees.

Now consider another relationship set called Manages between the Employees
and Departments entity sets such that each department has at most one
manager, although a single employee is allowed to manage more than one
department. The restriction that each department has at most one manager is an
example of a key constraint, and it implies that each Departments entity appears
in at most one Manages relationship in any allowable instance of Manages.
This restriction is indicated in the ER diagram of Figure 2.6 by using an arrow from
Departments to Manages. Intuitively, the arrow states that given a Departments
entity, we can uniquely determine the Manages relationship in which it appears.

Key Constraint on Manages

An Instance of the Manages Relationship Set

While this is also a potential instance for the WorksJn relationship set, the
instance of Works_In shown in Figure violates the key constraint on Manages.
EMPLOYEES MANAGES
DEPARTMENTS
Partial participation One to Many
Total participation

A relationship set like Manages is sometimes said to be one-to-many, to indicate


that one employee can be associated with many departments (in the capacity of a
manager), whereas each department can be associated with at most one
employee as its manager.

In contrast, the works-.In relationship set, in which an employee is allowed to


work in several departments and a department is allowed to have several
employees, is said to be many-to-many.

If we add the restriction that each employee can manage at most one department
to the Manages relationship set, which would be indicated by adding an arrow
from Employees to Manages in Figure , we have a one-to-one relationship set.

Key Constraints for Ternary Relationships


we show a ternary relationship with key constraints. Each employee works in at
most one department and at a single location. An instance of the Works_In3
relationship set is shown in Figure . Note that each department can be associated
with several employees and locations and each location can be associated with
several departments and employees; however, each employee is associated with
a single department and location.

A Ternary Relationship Set with Key Constraints

Participation Constraints

Let us say that every department is required to have a manager. This requirement
is an example of a participation constraint; the particip::ltion of the entity set
Departments in the relationship set Manages is said to be total. A participation
that is not total is said to be partial.
Weak Entity Sets

An Entity set may not have sufficient attributes to form a primary key , such an
entity set is termed as weak entity set.

An Entity set that has a primary key is termed as a strong entity set

Every weak set is to be meaningful, it must be associated with another entity set
called identifying or owner entity set.

Every weak entity must be associated with an identifying entity.


The relationship associating the weak entity set with the identifying entity set is
called the identifying relationship.

From the figure we consider

1 The relationship is one-to-one relationship.


2 although a weak entity set does not have primary key we need to
distinguish among all the entities.
3 The primary key of the weak entity set is formed by the primary key of the
owner or identifying set.
4 A weak entity set can participate in relationships other than the identifying
relationship

Class Hierarchies

1. Specialization

The process of designating subgroupings within an entity set is called


specialization

Ex

From the above example

1. Saving account is an account


2. Checking account is an account

From the above example two specialization of accounts. i.e saving account and
checking account

The account entity is described by the attributes account number and


balance.

The entityset savings-account would have all the attributes of account


and an additional attribute interest-rate.

The entityset checking-account would have all the attributes of account


and an additional attribute overdraft-amount.
It is a top-down approach. Specialization is shown by a triangle component
labeled ISA
The label ISA stands for “is a”

Example customer is a person

The high and lower level entity sets are shown as regular entity sets

From the above example account is a higher level entity , savings account
and checking accounts are the lower level enities

2 Generalization

1. Identifying the common attributes from two different entities is called


generalization
2. It is simply the inversion of the specialization.
3. It is a bottom up approach
4. Consider an example for generalization that is employee
These employee have attributes like officer,teller,secretary.
Officer entity may be described further by the attributes office-number
Teller entity may be described further by the attributes station-number
hours-worked
Secretary may described further by the attributed hours-worked.
Aggregation

Aggregation allows us to indicate that a relationship set (identified through a


dashed box) participates in another relationship set. This is illustrated in Figure
2.13, with a dashed box around Sponsors (and its participating entity sets) used to
denote aggregation. This effectively allows us to treat Sponsors as an entity set
for purposes of defining the Monitors relationship set.

we use it when we need to express a relationship among relationships.


CONCEPTUAL DESIGN WITH THE ER MODEL

Developing an ER diagram presents several choices, including the following:

1 Should a concept be modeled as an entity or an attribute / an entity or a


relationship?

2 What are the relationship sets and their participating entity sets? Should
we use binary or ternary relationships? Or aggregation?

1 Entity versus Attribute

it is sometimes not clear whether a property should be modeled as an attribute or


as an entity set.

For example, consider adding address information to the Employees entity set.
One option is to use an attribute address. This option is appropriate if we need to
record only one address per employee, and an address as a string.
An alternative is to create an entity set called Addresses and to record
associations between employees and addresses using a relationship (say,
Has_Address).
This more complex alternative is necessary in two situations:

• We have to record more than one address for an employee.


• We want to capture the structure of an address in our ER diagram. For example,
we might break down an address into city, state, country, and Zip code, in
addition to a string for street information. By representing an address as an entity
with these attributes

case 1:

For another example of when to model a concept as an entity set rather than an
attribute, consider the relationship set (called Works:n4)
The Works_In4 Relationship Set

in that it has attributes FROM and to, instead of since. Intuitively, it records the
interval during which an employee works for a department .
The problem is that we want to record several values for the descriptive attributes
for each instance of the Works-ln2 relationship .

We can address this problem by introducing an entity set called, say, Duration,
with attributes from and to,
Entity versus Relationship

We assumed that a bank loan is modeled as an entity .


Customer Table
Cust-id Cust-named Street City
321-12-3123 Ram Main Nellore
123-87-6754 Shyam North Gudur
543-98-7854 Ganesh South Chennai
342-78-7634 Suresh Spring Bangalore
876-65-2367 Mahesh Main Hyderabad

Loan Table

Loan-ID Balance
L-17 1000
L-23 1500
L-87 2000
L-26 2300
L-54 2340

An alternative is to model a loan not as an entity, A Relationship between


customers and branches.
If every loan is held by exactly one customer and is associated with exactly
one branch.
We cannot represent a situation is which several customers hold a loan
jointly
To handle such situation , we must define a separate relationship for each
holder of the joint loan.

Binary versus Ternary Relationships:

Consider the ER diagram

an employee can own several policies, each policy can be owned by several
employees, and each dependent can be covered by several policies.

Suppose that we have the following additional requirements:

1 A policy cannot be owned jointly by two or more employees.


2. Every policy must be owned by some employee.
3. Dependents is a weak entity set, and each dependent entity is uniquely
identified by taking pname in conjunction with the policyid of a policy entity
(which, intuitively, covers the given dependent).
The first requirement suggests that we impose a key constraint on Policies with
respect to Covers, but this constraint has the unintended side effect that a policy
can cover only one dependent.
The second requirement suggests that we impose a total participation constraint
on Policies.

The third requirement forces us to introduce an identifying relationship that is


binary .
the best way to model this situation is to use two binary relationships, as shown
in Figure 2.18.

Ternary relationship

As a typical example of a ternary relationship, consider entity sets Parts,


Suppliers, and Departments, and a relationship set Contracts (with descriptive
attribute qty) that involves all of them. A contract specifies that a supplier will
supply (some quantity of) a part to a department.
Aggregation versus Ternary Relationships

For example, consider the ER diagram shown in Figure 2.13.


According to this diagram, a project can be sponsored by any number of
departments, a department can sponsor one or more projects, and each
sponsorship is monitored by one or more employees.
we might reasonably use a ternal'Y relationship, say, Sponsors2, as shown
in Figure 2.19.
Consider the constraint that each sponsorship (of a project by a department) be
monitored by at most one employee. We cannot express this constraint in terms
of the Sponsors2 relationship set. On the other hand, we can easily express the
cOnstraint by drawing an arrow from the aggregated relationship Sponsors to the
relationship Monitors in Figure 2.13. Thus, the presence of such a constraint
serves &s another reason for using aggregation rather than a ternary relationship
set.
CONCEPTUAL DESIGN FOR LARGE ENTERPRISES

For a large enterprise, the design may require the efforts of more than one
designer and span data and application code used by a number of user groups.

Using a high-level, semantic data model, such as ER diagrams, for conceptual


design in such an environment offers the additional advantage that the high-level
design can be diagrammatically represented and easily understood by the many
people who must provide input to the design process.

An important aspect of the design process is the methodology used to structure


the development of the overall design and ensure that the design takes into
account all user requirements and is consistent.

The usual approach is that the requirements of various user groups are
considered, any conflicting requirements are somehow resolved, and a single set
of global requirements is generated at the end of the requirements analysis
phase.

Generating a single set of global requirements is a difficult task, but it allows the
conceptual design phase to proceed with the development of a logical schema
that spans all the data and applications throughout the enterprise.

An alternative approach is to develop separate conceptual scheMa. for different


user groups and then integTate these conceptual schemas.

THE UNIFIED MODELING LANGUAGE

UML, like the ER model, has the attractive feature that its constructs can be
drawn as diagrams. It encompasses a broader spectrum of the software design
process than the ER model:
I. Business Modeling:

In this phase, the goal is to describe the business processes involved in


the software application being developed.
II. System Modeling:

The understanding of business processes is used to identify the


requirements for the software application. One part of the requirements
is the database requirements.

III Conceptual Database Modeling:

This step corresponds to the creation of the ER design for the database. For
this purpose, UML provides many constructs that parallel the ER constructs.

IV Physical Database Modeling:

UML also provides pictorial representations for physical database design


choices, such As the creation of table spaces and indexes.

V Hardware System Modeling:

UML diagrams can be used to describe the hardware configuration used for the
application.

There are many kinds of diagrams in UML.

Use case diagrams describe the actions performed by the system in response to
user requests, and the people involved in these actions.

Activity diagrams Show the flow of actions in a business process.


Statechart diagrams describe dynamic interactions between system objects.
These diagrams, used in busine.c;s and systern modeling, describe how the
external functionality is to be implemented, consistent with the business rules
and processes of the enterprise.

Class diagrams are similar to ER diagrams, although they are more general in that
they are intended to model application entities (intuitively, important program
components) and their logical relationships in addition to data entities and their
relationships.
Database Users :
The main goal of a database system is to provide an environment for retrieving
information from and storing new information into the database

There are four different types of database system users


1 Naïve Users
2 Application Users
3 Sophisticated Users
4 Specialised Users

1 Naïve Users

These are the unsophisticated users who interact with the system by
permanent application programs that have been written previously.

For example : a bank teller who needs to transfer 50 Rs from Account A to


Account B invokes a program called transfer . This program asks the teller for the
amount of money to be transferred ,the account from which to which the money
is to be transferred . These are also called as end users

2 Application Programmers

Application Programmers are computer professionals who interact with the


system through DML calls, Which are embedded in a program written in a host
language
The host language is also called high level language. The high level
languages are COBIL,PASCAL,C,C++ ,Etc.

3 Sophisticated Users

These Sophisticated Users interact with the system without writing


programs , instead their requests in a database query language.
Query language involes the information retrieval ex : Analyst.

4 Specialized Users
These users are the sophisticated users who write specialized database
applications
They can interact the database with the DDL and DML Statements.
These also maintain the graphics data and video and audio data.

Database Adminstrator
The Person who has such central control over the system is called
database administrator (DBA).

1. Schema definition :
The DBA creates the original database schema by executing a set
of data definition statements in the DDL

2 Storage Structure and access method definition


In this the administrator is going to store the different types of
data such as audio, video etc., He can also change the structure of the
stored data.

3.Schema and physical organization modification :


The DBA carries out changes to the schema and physical organization
to reflect the changing needs of the organization or to alter the physical
organization to improve performance.

4. Granting of authorization for data access :


By granting different types of authorization the database
administrator can regulate which parts of the database various users can
access .
The authorization information is kept in a special system structure that
the database System consults whenever someone attempts to access the
data in the system .

5. Routine Maintaince :
1 Periodically backing uo the database .
2 Ensure that enough free disk space is available for normal operations
and upgrading disk space is required .
3 Monitoring jobs running on the database and ensure that
performance is not degraded by very expensive tasks submitted by
some users

Database system Structure :

The database system is partitioned into modules that deal with each
of the responsibilities of the overall system.
The functional components of a database is divided into two types.
1. Storage Manager
2. Query Processor

1. Storage Manager

A Storage Manager is a program module that provides the


interface between the low level data stored in the database and
application programs , queries submitted to the system.

The storage manager is responsible for the interaction with the


file manager.

The storage manager translates the various DML statements into


low level file system commands.

The storage manager is responsible for storing , retrieving ,


updating data in the database.

The storage manager components includes :

Authorization and Integrity manager :


Which tests for the satisfaction of integrity , constraints
and checks the authority of user to access data .

Transaction manager :

Which ensures that the database remains in a consistent state and


current transaction executions proceed without conflicting.

File Manager :

Which manages the allocation of space on disk storage and the data
structure used to represent information stored on disk.

Buffer Manager :

Which is responsible for fetching data from disk storage into main
memory and deciding what data to cache in main memory .

This is the critical part of the data base . It handles the database sizes
that are much larger than the size of main memory.

The storage manager implements several data structures as part of


the physical system implementation.

Data files which store the database itself .

Data dictionary which stores metadata about the structure of the


database in particular the schema of the data base

2. Query Processor

The query processor components includes :

1. DDl interpreter : Which interprets DDl statements and records the


definitions in the data dictionary.
2. DML compiler which translates DML statements in a query language
into an evaluation plan consisting of low-level instructions that the
query evaluation engine understands.
3. The DML compiler also performs query optimization that is it picks
that lowest cost evaluation plan from the alternatives .

Query evaluation engine :

Which executes low level instructions generated by the DML


Statements .

1.INTRODUCTION TO THE RELATIONAL MODEL


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 novice users to understand the contents of a
database, and it permits the use of simple, high-level languages to query the data.

The main construct for representing data in the relational model is a relation.

A relation consists of a relation schema and a relation instance. The relation instance is a table,
and the relation schema describes the column heads for the table.

The schema specifies the relation's name, the name of each field (or column, or 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.

We use the example of student information in a university database

Students(sid: string, name: string, login: string, age: integer, gpa: real);

This says, for instance, that the field named sid has a domain named string.
The set of values associated with domain string is the set of all character strings.

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 schema. 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.

Table contains six tuples and has, as we expect from the schema, five fields. Note that no two
rows are identical.
In practice, commercial systems allow tables to have duplicate rows.

The degree, also called arity, of a relation is the number of fields.

The cardinality of a relation instance is the number of tuples in it .

A relational database is a collection of relations with distinct relation names.

The relational database schema is the collection of schemas for the relations in the database.

For example,
A university database with relations called Students, Faculty, Courses, Rooms, Enrolled,
Teaches.

2. Creating and Modifying Relations Using SQL

The CREATE TABLE statement is used to define a new table.


To create the Students relation, we can use the following statement:

CREATE TABLE Students


( sid CHAR(20) ,

Name char (20),


Login char (10),
Age integer,
Gpa real
);

Tuples are inserted ,using the INSERT command. We can insert a single tuple into the Students
table as follows

INSERT INTO STUDENT VALUES (53688, 'Smith', 'smith@ee', 18, 3.2);

We can delete tuples using the DELETE command. We can delete all Students tuples with name
equal to Smith using the command:

DELETE
FROM Student
WHERE name = 'Smith'

We can modify the column values in an existing row using the UPDATE command.
For example, we can increment the age and decrement the gpa of the student with sid 53688:

UPDATE Students
SET age = age + 1, gpa = gpa - 1
WHERE sid = 53688;

The WHERE clause is applied first and determines which rows are to be modified.
The SET clause then determines how these rows are to be modified. If the column being
modified is also used to determine the new value, the value used in the expression on the right
side of equals (=) is the old value, that is, before the modification.

3. INTEGRITY CONSTRAINTS OVER RELATIONS

An integrity constraint (Ie) is a condition specified on a database schema and restricts the data
that can be stored in an instance of the database.

If a database instance satisfies all the integrity constraints specified on the database schema, it
is a legal instance.

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.
A set of fields that uniquely identifies a tuple according to a key constraint is called a candidate
key for the relation;

Key constratints :

1. Primary Key constraints :

1. Primary key may be defined as the key which has one or more columns in a table
used uniquely to identify each row in a table.
2. Single column primary key is called as simple primary key.
3. Multi column primary key is called as composite primary key.
4. This primary key is defined in either create table statement or alter table statement

Features of primary key.


1. Primary key is a column or set of columns that are uniquely identifies a row.
2. Primary key will not allow duplicate values.
3. Primary key does not allow NULL values .
4. Only one primary key is allowed for a table.

CREATE TABLE Students (


sid CHAR(20) ,

name CHAR(30),

login CHAR (20) ,

age INTEGER,

PRIMARY KEY (sid),


);
This definition says that sid is the primary key .

Foreign Key Constraints

Sometimes the information stored in a relation is linked to the information stored in another
relation. If one of the relations is modified, the other must be checked, and perhaps modified,
to keep the data consistent.

 Foreign key is with reference constraints which represents the relationship between tables.

 Foreign key is a primary key of another table.

 Foreign key can be at column level or table level.

 Foreign key is derived from primary key or unique key of some other table.

 The table in which foreign key is defined is called a foreign table or detail table.

CREATE TABLE Students (


sid CHAR(20) ,
name CHAR(30),
login CHAR (20) ,
age INTEGER,
honorsCHAR(10) NOT NULL,
gpa REAL)
PRIMARY KEY (sid),
FOREIGN KEY (honors) REFERENCES Courses (cid)
);

4.General Constraints

general constraints in the form of table constraints and assertions.


Table constraints are associated with a single table and checked whenever that table is
modified.
In contrast, assertions involve several tables and are checked whenever any of these tables is
modified.

Transactions and Constraints

A program that runs against a database is called a transaction, and it can contain several
statements (queries, inserts, updates,etc.) that access the database.

By default, a constraint is checked at the end of every SQL statement that could lead to a
violation, and if there is a violation, the statement is rejected

5. QUERYING RELATIONAL DATA:

A relational database query (query, for short) is a question about the data, and the answer
consists of a new relation containing the result. For example, we might want to find all students
younger than 18 or all students enrolled in . A query language is a specialized language for
writing queries.

SQL is the most popular commercial query language for a relational DBMS.

SELECT * FROM Students WHERE S.age < 18 ;

The symbol *, means that we retain all fields of selected tuples in the result.
6. LOGICAL DATABASE DESIGN: ER TO RELATIONAL
Entity Sets to Tables

The following SQL statement captures the preceding information, including the
domain constraints and key information:

CREATE TABLE Employees (


ssn CHAR(11),
name CHAR(30) ,
lot INTEGER,
PRIMARY KEY (ssn)
)
Relationship Sets (without Constraints) to Tables

All the available information about the Works-ln2 table is captured by the following SQL
definition:

);

Finally, consider the Reports_To relationship set shown in Figure 3.11.


Translating Relationship Sets with Key Constraints

Consider the relationship set Manages shown in Figure 3.12

Translating Relationship Sets with Participation Constraints


Translating Weak Entity Sets
Translating Class Hierarchies
Translating ER Diagrams with Aggregation
ER to Relational: Additional Examples

Consider the ER diagram shown in Figure 3.17. We can use the key constraints
7. INTRODUCTION TO VIEWS

A view is a table whose rows are not explicitly stored in the database but are computed as
needed from a view definition.

A view in SQL is a logical subset of data from one or more tables. View is used to restrict data
access

Consider the Students and Enrolled relations. Suppose we are often interested in finding the
names and
student identifiers of students who got a grade of B in some course, together with the course
identifier. \Ne can define a view for this purpose.
Syntax for creating a View,

CREATE or REPLACE view view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

Example

CREATE VIEW B-Students (name, sid, course)


AS SELECT S.sname, S.sid, E.cid
FROM Students S, Enrolled E
WHERE S.sid = E.studid AND E.grade = 'B'

This view can be used just like a base table, or explicitly stored table, in defining new queries or
views .

Example of Displaying a view :

SELECT * FROM B-Students.


FORCE VIEW CREATION

Force keyword is used while creating a view. This keyword force to create View even if the table
does not exist. After creating a force View if we create the base table and enter values in it, the
view will be automatically updated.

Syntax for forced View is,


CREATE or REPLACE force view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Update a View

Update command for view is same as for tables.

Syntax to Update a View is,


UPDATE view-name
set value
WHERE condition;
If we update a view it also updates base table data automatically

DESTROYING/ALTERING TABLES AND VIEWS

A vipw can be dropped using the DROP VIEW command, which is just like DROP TABLE

ALTER TABLE modifies the structure of an existing table. To add a column called maiden-name
to Students, for example, we would use the following command:

You might also like