Introduction to Database Management Systems
Introduction to Database Management Systems
What is DBMS?:
DBMS is a ccollection of interrelated data and a set of programs to access the data. It
provide an environment that is both convenient and efficient to use.
Applications of DBMS
Following are the list of applications of DBMS:
Banking: transactions
Airlines: reservations, schedules
Universities: registration, grades
Sales: customers, products, purchases
Online retailers: order tracking, customized recommendations
Manufacturing: production, inventory, orders, supply chain
Human resources: employee records, salaries, tax deductions
1
Database Systems I
2
Database Systems I
3
Database Systems I
Levels of Abstraction:
Physical level: describes how a record (e.g., customer) is stored.
Logical level: describes data stored in database, and the relationships among the
data.
o type instructor = record
ID : string;
name : string;
dept_name : string;
salary : integer;
end;
View level: application programs hide details of data types. Views can also hide
information (such as an employee’s salary) for security purposes.
View of Data:
An Architecture for a Database System:
4
Database Systems I
Data Models:
Data models define how the logical structure of a database is modelled. Data
Models are fundamental entities to introduce abstraction in a DBMS.
Data models define how data is connected to each other and how they are
processed and stored inside the system.
Data Model is a collection of conceptual tools for describing data, data
relationships, data semantics, and consistency constraints.
A data model provides a way to describe the design of a database at the physical,
logical, and view levels.
Historically, the network data model and the hierarchical data model preceded the
relational data model. These models were tied closely to the underlying implementation,
and complicated the task of modelling data.
Relational Model:
• The relational model uses a collection of tables to represent both data and the
relationships among those data. Each table has multiple columns, and each column
has a unique name.
• Tables are also known as relations.
• The relational model is an example of a record-based model.
• Record-based models are so named because the database is structured in fixed-
format records of several types. Each table contains records of a particular type.
• Each record type defines a fixed number of fields, or attributes.
• The columns of the table correspond to the attributes of the record type.
• The relational data model is the most widely used data model, and a vast majority
of current database systems are based on the relational model.
5
Database Systems I
6
Database Systems I
Relational DBMS:
• A database management system that stores data in the form of related tables is
called Relational Database Management System.
• Edgar F. Codd at IBM invented the relational database in 1970.
• Relational databases help solve problems as they are designed to create tables &
then combine the information in interesting ways to create valid information.
Database Schema:
• A database schema is a way to logically group objects such as tables, views, stored
procedures etc.
• Think of a schema as a container of objects.
7
Database Systems I
Normalization:
Normalization is the process of organizing the data in the
database. Normalization is used to minimize the redundancy from a relation or set
of relations.
It is also used to eliminate the undesirable characteristics like Insertion, Update
and Deletion Anomalies.
A table is 1NF if every cell contains a single value, not a list of values. This properties is
known as atomic. 1NF also prohibits repeating group of columns such as item1, item2,..,
item N. Instead, you should create another.
8
Database Systems I
A table is 2NF, if it is 1NF and every non-key column is fully dependent on the primary
key. Furthermore, if the primary key is made up of several columns, every non-key
column shall depend on the entire set and not part of it.
A table is 3NF, if it is 2NF and the non-key columns are independent of each other’s. In
other words, the non-key columns are dependent on primary key, only on the primary
key and nothing else.
9
Database Systems I
This kind of data are naturally unique and there should never be duplicates
But much of the time there isn’t one piece of naturally unique data.
So you will make one instead. You will tell the database to generate a unique
column.
Most DBMSs help you to generate those kind of columns with these kind of
values.
These column refers to Primary Key.
10
Database Systems I
Defining Relationships:
Any Database begins with defining tables, vital next step is add relationships
among tables.
Because much of your data is naturally connected.
You are not trying to invent relationships that don’t exist. You are trying to
describe what’s already there.
Insert Anomaly:
11
Database Systems I
Update Anomaly:
Delete Anomaly:
• What will happen if we delete student 222
• Deleting a row will delete all the records exist in that row.
Relationship:
A relationship, in the context of databases, is a situation that exists between two
relational database tables when one table has a foreign key that references the primary
key of the other table.
One-to-One Relationship:
In a one-to-one relationship, one record in a table is associated with one and only one
record in another table.
For example, in a school database, each student has only one student ID, and each
student ID is assigned to only one person.
12
Database Systems I
One-to-Many Relationship:
In a one-to-many relationship, one record in a table can be associated with one or more
records in another table.
For Example, One department can have Many students. So the relation is One-to-Many
between department and student table
Information about student and department are different but they are related to each
other. So we need to formally describe relationships between our tables
13
Database Systems I
dID in Student table is not a primary key but Foreign Key and it is not unique.
A foreign key is a column or group of columns in a relational database table that provides
a link between data in two tables. It acts as a cross-reference between tables because it
references the primary key of another table, thereby establishing a link between them.
Either we can go from the Department row or get dID then go to Student table and
get all students of the department.
Or we can go from the Student row and get dID then go to Department table and
find which student is associated with that department
14
Database Systems I
Many-to-Many Relationship:
A many-to-many relationship occurs when multiple records in a table are associated with
multiple records in another table.
Some people try this model, adding another column to the Book table.
However, adding new columns to your table means repeating same information
again.
This is a bad idea and it is discouraged in database design.
15
Database Systems I
Some other people think to cheat little bit. Something quick and dirty: Adding two
values into that sID column
Now AuthorID relates two author, But this’s also cheat like adding a new column.
This is highly discouraged as well.
So how do we solve this?
We go back to old tables with no official reference between them.
What we do to create many to many relationship is we add another table.
Only reason for this table to exist is to join the Author table and the Book table
together.
We set up two one to many relationship.
By using this we can go from Student to StudentCourse, find a cID and map that to
Course table.
16
Database Systems I
17
Database Systems I
About MS-Access:
Microsoft Access is a Database Management System (DBMS) from Microsoft that
combines the relational Microsoft Jet Database Engine with a graphical user interface and
software development tools. It is a member of the Microsoft Office suite of applications,
included in the professional and higher editions.
MS Access uses “objects" to help the user list and organize information, as well as
prepare specially designed reports. When you create a database, Access offers you
Tables, Queries, Forms, Reports, Macros, and Modules. Databases in Access are
composed of many objects but the following are the major objects −
Tables
Queries
Forms
Reports
Together, these objects allow you to enter, store, analyze, and compile your data.
Here are some of the most common data types you will find used in a typical Microsoft
Access database.
18
Database Systems I
If you use previous versions of Access, you will notice a difference for two of those
data types.
In Access 2013, we now have two data types — short text and long text. In
previous versions of Access these data types were called text and memo.
The text field is referred to as short text and your memo field is now called long
text.
Here are some of the other more specialized data types, you can choose from in Access.
19
Database Systems I
20
Database Systems I
Input Mask:
An input mask is a string of characters that indicates the format of valid input values. You
can use input masks in table fields, query fields, and controls on forms and reports. The
input mask is stored as an object property.
You use an input mask when it’s important that the format of the input values is
consistent. For example, you might use an input mask with a field that stores phone
numbers so that Access requires ten digits of input. If someone enters a phone number
without the area code, Access won’t write the data until the area code data is added.
0 for required numbers from 0-9 and 9 for optional numbers from 0-9
21
Database Systems I
The following table lists the placeholder and literal characters for an input mask and
explains how it controls data entry:
Validation Rule:
You can vet or validate data in Access desktop databases as you enter it by using
validation rules. You can use the expression builder to help you format the rule correctly.
Validation rules can be set in either table design or table datasheet view. There are three
types of validation rules in Access:
1. Field Validation Rule: You can use a field validation rule to specify a criterion that all
valid field values must meet.
2. Record Validation Rule: You can use a record validation rule to specify a condition
that all valid records must satisfy.
3. Validation on a form: You can use the Validation Rule property of a control on a form
to specify a criterion that all values input to that control must meet.
22
Database Systems I
23
Database Systems I
24
Database Systems I
The where clause specifies conditions that the result must satisfy
o Corresponds to the selection predicate of the relational algebra.
To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
Comparison results can be combined using the logical connectives and, or, and
not.
Comparisons can be applied to results of arithmetic expressions.
25
Database Systems I
Joins:
For all instructors who have taught some course, find their names and the course
ID of the courses they taught.
select name, course_id
from instructor, teaches
where [Link] = [Link]
Find the course ID, semester, year and title of each course offered by the Comp.
Sci. department
26
Database Systems I
Example:
List the names of instructors along with the course ID of the courses that they taught.
String Operations:
SQL includes a string-matching operator for comparisons on character strings. The
operator “like” uses patterns that are described using special characters:
percent (*). The * character matches any substring.
Find the names of all instructors whose name includes the substring “dar”.
27
Database Systems I
select name
from instructor
where name like ‘*dar*‘
Null Values:
It is possible for tuples to have a null value, denoted by null, for some of their attributes
null signifies an unknown value or that a value does not exist.
28
Database Systems I
select name
from instructor
where salary is null
Aggregate Functions:
These functions operate on the multiset of values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
29
Database Systems I
All aggregate operations except count(*) ignore tuples with null values on the
aggregated attributes
30
Database Systems I
Chapter 4: Queries
31
Database Systems I
Increase salaries of instructors whose salary is over $1000 by 3%, and all others receive
a 5% raise
Write two update statements:
update instructor
set salary = salary * 1.03
where salary > 1000;
update instructor
set salary = salary * 1.05
where salary <= 1000;
The order is important
Referential Integrity:
32
Database Systems I
History:
• IBM Sequel language developed as part of System R project at the IBM San Jose
Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86, SQL-89, SQL-92
– SQL:1999, SQL:2003, SQL:2008
• Commercial systems offer most, if not all, SQL-92 features, plus varying feature
sets from later standards and special proprietary features.
– Not all examples here may work on your particular system.
33
Database Systems I
35
Database Systems I
36
Database Systems I
Increase salaries of instructors whose salary is over $1000 by 3%, and all others receive
a 5% raise
Write two update statements:
update instructor
set salary = salary * 1.03
where salary > 1000;
update instructor
set salary = salary * 1.05
where salary <= 1000;
The order is important
37
Database Systems I
• Find the names of all departments with instructor, and remove duplicates
select distinct dept_name
from instructor
• The keyword all specifies that duplicates not be removed.
select all dept_name
from instructor
• An asterisk (*) in the select clause denotes “all attributes”
select *
from instructor
• The select clause can contain arithmetic expressions involving the operation, +, –
, *, and /, and operating on constants or attributes of tuples.
• The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor relation, except that the
value of the attribute salary is divided by 12.
38
Database Systems I
Joins:
• For all instructors who have taught some course, find their names and the course
ID of the courses they taught.
select name, course_id
from instructor, teaches
where [Link] = [Link]
• Find the course ID, semester, year and title of each course offered by the Comp.
Sci. department
select section.course_id, semester, year, title
from section, course
where section.course_id = course.course_id and dept_name = ‘Comp. Sci.'
Natural Join:
• Natural join matches tuples with the same values for all common attributes, and
retains only one copy of each common column
select *
from instructor natural join teaches;
39
Database Systems I
• List the names of instructors along with the course ID of the courses that they
taught.
String Operations:
• SQL includes a string-matching operator for comparisons on character strings.
The operator “like” uses patterns that are described using two special characters:
– percent (%). The % character matches any substring.
– underscore (_). The _ character matches any character.
40
Database Systems I
• Find the names of all instructors whose name includes the substring “dar”.
select name
from instructor
where name like '%dar%'
• Match the string “100 %”
like ‘100 \%' escape '\'
• Patterns are case sensitive.
• Pattern matching examples:
– ‘Intro%’ matches any string beginning with “Intro”.
– ‘%Comp%’ matches any string containing “Comp” as a substring.
– ‘_ _ _’ matches any string of exactly three characters.
– ‘_ _ _ %’ matches any string of at least three characters.
• SQL supports a variety of string operations such as
select concat(fname,’ ’,lname) as fullname, age
from student
41
Database Systems I
Aggregate Functions:
These functions operate on the multiset of values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
42
Database Systems I
All aggregate operations except count(*) ignore tuples with null values on the
aggregated attributes
43
Database Systems I
Modeling:
A database can be modeled as:
a collection of entities,
relationship among entities.
An entity set is a set of entities of the same type that share the same properties.
Example: set of all persons, companies, trees, holidays
Relationship Sets:
A relationship is an association among several entities
Example:
44553 (Peltier) advisor 22222 (Einstein)
student entity relationship set instructor entity
44
Database Systems I
45
Database Systems I
Attributes:
An entity is represented by a set of attributes, which is descriptive properties
possessed by all members of an entity set.
o Example:
o instructor = (ID, name, street, city, salary )
course= (course_id, title, credits)
Domain – the set of permitted values for each attribute
Attribute types:
o Simple and composite attributes.
o Single-valued and multivalued attributes
Example: multivalued attribute: phone_numbers
o Derived attributes
Can be computed from other attributes
Example: age, given date_of_birth
Composite Attributes
46
Database Systems I
Note: Some elements in A and B may not be mapped to any elements in the other set
Note: Some elements in A and B may not be mapped to any elements in the other set
47
Database Systems I
Keys:
A super key of an entity set is a set of one or more attributes whose values
uniquely determine each entity.
A candidate key of an entity set is a minimal super key
o ID is candidate key of instructor
o course_id is candidate key of course
Although several candidate keys may exist, one of the candidate keys is selected
to be the primary key.
The combination of primary keys of the participating entity sets forms a super key
of a relationship set.
o (s_id, i_id) is the super key of advisor
o NOTE: this means a pair of entity sets can have at most one relationship
in a particular relationship set.
Example: if we wish to track multiple meeting dates between a
student and her advisor, we cannot assume a relationship for each
meeting. We can use a multivalued attribute though
Must consider the mapping cardinality of the relationship set when deciding what
are the candidate keys
Need to consider semantics of relationship set in selecting the primary key in case
of more than one candidate key
Redundant Attributes:
Suppose we have entity sets
o instructor, with attributes including dept_name
o department
and a relationship
o inst_dept relating instructor and department
Attribute dept_name in entity instructor is redundant since there is an explicit
relationship inst_dept which relates instructors to departments
o The attribute replicates information present in the relationship, and should
be removed from instructor
o BUT: when converting back to tables, in some cases the attribute gets
reintroduced, as we will see.
48
Database Systems I
E-R Diagrams:
Entity-Relationship (E-R) diagram is a graphical/ pictorial representations of Entities and
their Relationship.
49
Database Systems I
Roles:
Entity sets of a relationship need not be distinct
o Each occurrence of an entity set plays a “role” in the relationship
The labels “course_id” and “prereq_id” are called roles.
Cardinality Constraints:
We express cardinality constraints by drawing either a directed line (),
signifying “one,” or an undirected line (—), signifying “many,” between the
relationship set and the entity set.
One-to-one relationship:
o A student is associated with at most one instructor via the relationship
advisor
o A student is associated with at most one department via stud_dept
One-to-One Relationship:
50
Database Systems I
One-to-Many Relationship:
Many-to-One Relationships:
Many-to-Many Relationship:
51
Database Systems I
52
Database Systems I
Note: the primary key of the strong entity set is not explicitly stored with the weak
entity set, since it is implicit in the identifying relationship.
If course_id were explicitly stored, section could be made a strong entity, but then
the relationship between section and course would be duplicated by an implicit
relationship defined by the attribute course_id common to course and section
53
Database Systems I
54