Sunteți pe pagina 1din 73

Introduction to Database

Management Systems (DBMS)


Presented by
Eng. Reem E. Mohamed
Course Agenda
Basic Concepts
Structured Query Language (SQL)
Not only SQL (NoSQL)
Course Plan
Day 1
Basic Concepts of Database
Create ERD
Day2
Structured Query Language (SQL)
Mapping and DDL with an example
DML with examples
NoSQL database overview
Basic Concepts
File based System Approach and its limitations
Definitions
Database, Database Management System (DBMS), Database System
DBMS
Advantages/ Disadvantages
Users
Architecture
Data Models
Mappings and Data Independence
Entity Relationship Modeling
Types of Attributes
Relationships
ER-to relational mapping
File based System Approach and its
limitations
It is a collection of programs that perform services for the end user.
Ex: MS-word and Excel sheet
Limitations of file based system
Separation & Isolation Of data
Duplication Of data
Program Data Dependence
Incompatible File Formats
Definitions
Database: A collection of related data.
Database Management System (DBMS): A software
package/ system to facilitate the creation and maintenance
of a computerized database.
Database System: The DBMS software together with the
data itself. Sometimes, the applications are also included. (
Software + Data )
Database Management System (DBMS)
Users
Database System
Application Programs

DBMS Software to process


Software Queries

Software to access Stored Data

Stored DB
Stored
Definition
Database
(Metadata)
DBMS Advantages
Controlling Redundancy.
Restricting Unauthorized Access.
Sharing data.
Enforcing Integrity Constraints
Inconsistency can be avoided.
Providing Backup and Recovery.
DBMS Disadvantages
Needs expertise to use (which is expensive)
DBMS is expensive
May be incompatible with any other available DBMS
Database Users
Database Administrator (DBA)
System Analysts
Database Designer
Application programmers
End users
Database Administrator (DBA) System Analyst Database Designer Application Programmer
Allocates space for DBMS Understands Designs DB Designs User Interface for
for installation and DB User according to the end user
deployment requirements analyst
DB backup and recovery Chooses DBMS recommendations
Db performance monitoring
Security
Example of real life project

Project that is aimed at monitoring senior peoples health using smart wearable devices
DBMS Three Level Schema/ Architecture
User models
External Schema 1 External Schema 2 External Schema 3 Viewed by
end user
Different Database Views
Logical models
Conceptual Schema Accessed by DBA
Logical model of all stored data

mapping
(tables and constraints)

Physical models
Physical Schema According to the type of the DBMS used
Data structure: how files are stored on the disk
Levels of Abstraction in a DBMS
(Three Schema Architecture) Disk
High Level (Conceptual) Physical
provide concepts that are close to describes how data is stored in
the way many users perceive data, the computer and the access
entities, attributes and relationships. path needed to access and
(Ex. ERD) search for data
Mapping and Data Independence
Mapping: It is the processes of transforming requests and results
between levels.
These mappings may be time-consuming. However, a certain amount
of mapping between the conceptual and internal levels is necessary.

Data Independence: The capacity to change the schema at one level


without having to change the schema at the next higher level. For
example, the ability to change internal schema without affecting the
conceptual one
Entity Relationship Modeling
Entity-Relationship Diagram (ERD): identifies information required by the
business by displaying the relevant entities and the relationships between
them.
Entity - An entity is a thing in the real world with an independent
existence. Physical existence (for example, a particular person, car) or
conceptual existence (for instance, a job, or a university course). Types of
entities: Weak- Regular
Weak Entity: An entity that does not have a key attribute
Attribute - The particular properties that describe the entity. An EMPLOYEE
entity may be described by the employees name, age, address and salary
attributes.
Types of Attributes
Key: an attribute whose values are distinct (unique) for each entity
and can be used to uniquely identify the record
Single Key: For example, SSN of EMPLOYEE
Composite Key: the combination of the attribute values that together form a key and must
be distinct for each entity. For example, ID and Application_no
Multi-valued: has a set of values for the same entity instance
Composite: can be divided into smaller subparts
Derived: can be calculated from another attribute or entity
Single/Simple: Attributes that are not divisible and have a single
value for a particular entity instance
Relationships
It is a connection between entity classes.
Factors for describing a relationship

1. Degree of a Relationship: is the number of participating entity

2. Cardinality Ratio: specifies the maximum number of relationship

3. Participation: specifies the minimum number of relationship


instances that each entity can participate with.
Relationships (cont.)

1. Degree of a Relationship
a. Unary/ Recursive Emp lead

b. Binary Emp work Dept

c. Ternary Supplier supply Part

Project
Relationships (cont.)
2. Cardinality Ratio (the word that is far from the table
name)
A. One to one Emp
1
manage
1
Dept
In mapping: check participation
B. One to many Emp
M 1
Dept
work
In mapping: P.K. in 1 F.K. in Many
C. Many to many
In mapping: make a new table with composite primary key
from each table in the relation M N
Emp work Proj
Relationships (cont.)
3. Participation (the word that is close to the table name)
a. Total/ Full Dependency/ Mandatory
b. Partial/ Partial Dependency/ Optional
How to Map 1-1 cardinality
1 1
Emp manage Dept Must-Must May-May May- Must
Merge tables Like P.K(may)
Partial Total Chose PK with 1-Many F.K.(must)
(May) (Must) min. storage
(Zero or more) (One or more) size
Participation Examples
- A department may hire many employees
-An Employee may have a car. ( Zero or more)
-A Car must be assigned to particular - An employee must be employed by a department
employee
(Department membership is Optional, Employee
membership is Mandatory)

Employee Has Car Department Hire Employee


SUMMARY OF ERD
Symbol
NOTATION Definition
Rectangles represent
REGULAR ENTITY
ENTITY CLASSES
(Noun) WEAK ENTITY TYPE

RELATIONSHIP TYPE
Relationships
E1 R E2
(Verbs) TOTAL PARTICIPATION OF E2 IN R
N
E1 R E2 CARDINALITY RATIO 1:N FOR E1:E2 IN R

ATTRIBUTE
Circles represent ATTRIBUTES
(Entity Properties) KEY ATTRIBUTE

Key attributes of entities MULTIVALUED ATTRIBUTE

are underlined COMPOSITE ATTRIBUTE

DERIVED ATTRIBUTE
ER-to-Relational Mapping
Step 1: Mapping of Regular Entity Types

Step 2: Mapping of Weak Entity Types

Step 3: Mapping of Multi-valued attributes.

Step 4: Mapping of Many-to-Many relationships.


Example
A company is organized into departments. Each department has a
unique name, a unique number, and a particular employee who
manages the department. A department may have several locations.

A department may control a number of projects, each of which has a


unique name, a unique number, and a single location. A project must
be controlled by department
Example
A company is organized into departments. Each department has a
unique name, a unique number, and a particular employee who
manages the department. A department may have several locations.

A department may control a number of projects, each of which has a


unique name, a unique number, and a single location. A project must
be controlled by department
Example (Contd)
We store employees name, social security number, address, salary,
gender and birth date. An employee must be assigned to one
department and must work on one or more projects, which are not
necessarily controlled by the same department. We keep track of the
number of hours per week that an employee works on each project.
We also keep track of the direct supervisor of each employee.

We want to keep track of the dependents of each employee for


insurance purposes. We keep each dependents first name, gender,
birth date and relationship to that employee.
Example (Contd)
We store employees name, social security number, address, salary,
gender and birth date. An employee must be assigned to one
department and must work on one or more projects, which are not
necessarily controlled by the same department. We keep track of the
number of hours per week that an employee works on each project.
We also keep track of the direct supervisor of each employee.

We want to keep track of the dependents of each employee for


insurance purposes. We keep each dependents first name, gender,
birth date and relationship to that employee.
Start Practice Online Link (page 1-3)
Mapping Result
Musicana Example
Musicana records have decided to store information on musicians who perform on their albums in a database.
The company has wisely chosen to hire you as a database designer.
Each musician that is recorded at Musicana has an ID number, a name, an address (street, city) and a phone
number.
Each instrument that is used in songs recorded at Musicana has a unique name and a musical key (e.g., C, B-flat,
E-flat).
Each album that is recorded at the Musicana label has a unique title, a copyright date, and an album identifier.
Each song recorded at Musicana has a unique title and an author.
Each musician may play several instruments, and a given instrument may be played by several musicians.
Each album has a number of songs on it, but no song may appear on more than one album.
Each song is performed by one or more musicians, and a musician may perform a number of songs.
Each album has exactly one musician who acts as its producer. A producer may produce several albums.
Design a conceptual schema for Musicana. Be sure to indicate all keys and cardinality constraints and any
assumptions that you make.
Musicana records have decided to store information on musicians
who perform on their albums in a database. The company has wisely
chosen to hire you as a database designer.
Each musician that is recorded at Musicana has an ID number, a
name, an address (street, city) and a phone number.
Each instrument that is used in songs recorded at Musicana has a
unique name and a musical key (e.g., C, B-flat, E-flat).
Each album that is recorded at the Musicana label has a unique title,
a copyright date, and an album identifier.
Each song recorded at Musicana has a unique title and an author.
Each musician may play several instruments, and a given instrument may
be played by several musicians.
Each album has a number of songs on it, but no song may appear on more
than one album.
Each song is performed by one or more musicians, and a musician may
perform a number of songs.
Each album has exactly one musician who acts as its producer. A producer
may produce several albums.
Design a conceptual schema for Musicana. Be sure to indicate all keys and
cardinality constraints and any assumptions that you make.
Start Practice Online Link (page 9)
Structured Query Language(SQL)
Introduction
Data Definition Language (DDL)
CREATE, ALTER, DROP, TRUNCATE
Data Manipulation Language (DML)
INSERT, UPDATE, DELETE, SELECT
Data Control Language (DCL)
Views and Indexes
Introduction
Database Schema

Attribute data types


1. Numeric: float, real, double Precision
2. Alphanumeric/ character string: char(), varchar().
3. Bit String: Bit(), BitVarying()
4. Boolean: [true, false, unknown]
5. Date: [YYYY:MM:DD]
Database Integrity Constraints (ICs)
Primary Key ( Not Null + Unique): preferred Numeric with
limited storage size
Not Null: foreign key in must participation
Unique Key: in case of composite primary key (telephone
number case)
Referential Integrity ( FK ): parent child relationship
To delete in parent, delete it child first
To insert in a child, insert in parent instead
Check : Range of accepted values
Structured Query Language (SQL)
Data Definition Language (DDL)
Data Manipulation Language (DML)
CREATE

Data
ALTER
Definition DROP
Language
(DDL)

TRUNCATE

(Auto commit) Cant be rolled back since changes in DB are on hard disk
CREATE Command
Syntax
CREATE TABLE table_name
(column1 DATA_TYPE [CONS_TYPE CONS_NAME],
column2 DATA_TYPE [CONS_TYPE CONS_NAME],... )
Example
CREATE TABLE Students
(ID NUMBER(15) PRIMARY KEY, First_Name CHAR(50) NOT
NULL, Last_Name CHAR(50), Address CHAR(50), City CHAR(50),
Country CHAR(25), Birth_Date DATE);
DROP Command
Syntax
DROP TABLE table_name

Example
DROP TABLE Students
ALTER Command
ALTER TABLE statement is used to update metadata (add or
drop columns) in an existing table.

Syntax
ALTER TABLE table_name ADD column_name datatype
ALTER TABLE table_name DROP column_name
ALTER Example
LastName FirstName Address
Pettersen Kari Storgt 20

To add a column named "City" in the "Person" table:


ALTER TABLE Person ADD City varchar(30)

Result:
LastName FirstName Address City
Pettersen Kari Storgt 20
Examples of well-know industrial-strength relational
DBMSes include
Oracle, Microsoft SQL Server, IBM DB2, Informix
Well-know PC-based (desktop) relational DBMSes include
Microsoft Access , Microsoft FoxPro, Borland dBase

Start Practice Online Link (page 4-7)


Structured Query Language (SQL)
Data Definition Language (DDL)
Data Manipulation Language (DML)
INSERT

Data
UPDATE
Manipulation DELETE
Language
(DML)

SELECT

Can be rolled back BEFORE commit


Metadata of Table Store_Information

INSERT Command Column Name Data Type


store_name char(50)
Sales float
Date datetime
Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
Example
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')

INSERT INTO Store_Information VALUES ('Los Angeles', 900,


'Jan-10-1999')
INSERT Example 2
LastName FirstName Address City
El-Sayed Mohamed Nasr City Cairo

INSERT INTO Students VALUES (Saleh, Ahmed', Moharam


bak', Alex.')
Result
LastName FirstName Address City
El-Sayed Mohamed Nasr City Cairo
Saleh Ahmed Moharam bak. Alex
UPDATE Command
Syntax
UPDATE table_name
SET column_1= new value, column_2= new value
WHERE condition
UPDATE Example
UPDATE Store_Information
SET Sales = 500
WHERE store_name = Los Angeles AND Date = Jan-08-1999
Before After
store_name Sales Date store_name Sales Date
Los Angeles $1500 Jan-05-1999 Los Angeles $1500 Jan-05-1999

San Diego $250 Jan-07-1999 San Diego $250 Jan-07-1999

Los Angeles $300 Jan-08-1999 Los Angeles $500 Jan-08-1999

Boston $700 Jan-08-1999 Boston $700 Jan-08-1999


DELETE Command
Syntax
DELETE FROM table_name
WHERE condition
DELETE Example
DELETE FROM Store_Information
WHERE store_name = Los Angeles

Before After
store_name Sales Date store_name Sales Date
Los Angeles $1500 Jan-05-1999 San Diego $250 Jan-07-1999

San Diego $250 Jan-07-1999 Boston $700 Jan-08-1999

Los Angeles $300 Jan-08-1999

Boston $700 Jan-08-1999


TRUNCATE Vs DELETE
TRUNCATE TABLE is functionally identical to DELETE
statement with no WHERE clause and once executed never
rolled back
It deletes all the data in the table
Syntax:
TRUNCATE TABLE table_name

Example:
TRUNCATE TABLE customer
Select Queries
Syntax

SELECT <attribute list >


FROM <table list>
WHERE <condition>
ORDER BY <attribute list >
DISTINCT Keyword
Its a row keyword that displays unique rows Employee table
SSN Ename Dnum Salary
100 Ahmed 2 5000
200 Mai 2 8000
Example 300 Ali 2 4000
SELECT DISTINCT Dnum 400 Mahmoud 3 10000
FROM Employee;
Output
DNum
2
3
Comparison Conditions
Employee table
List of comparison conditions: SSN Ename Dnum Salary
= Equal
100 Ahmed 2 5000
> greater than
>= greater than or equal 200 Mai 2 8000
< less than 300 Ali 2 4000
<= less than or equal
<>not equal 400 Mahmoud 3 10000

Example Output
SELECT Ename, Salary
FROM Employee Ename Salary
WHERE Salary >5000 Mai 8000
Mahmoud 10000
Other Comparison Conditions
BETWEEN AND .. (between two values
inclusive)

IN (set) (Match any of a list of values)


ALL ( set) (Match all values in the list)
Not IN (set) (Match any of a list of values)

LIKE (Match a character Pattern) ( _ under score stands for


any single character , % Percent stands for any sequence of n character
where n >= 0)
Logical Conditions
Employee table
List of Logical Operators SSN Ename Dnum Salary
AND 100 Ahmed 2 5000
OR 200 Mai 2 8000
NOT 300 Ali 2 4000
Example 400 Mahmoud 3 10000
SELECT SSN, Ename, Salary
FROM Employee Output
WHERE SSN NOT IN (100, 200, 300) SSN Ename Salary
AND Salary >5000; 400 Mahmoud 10000
Arithmetic Expressions and Order by Clause
(ASC, DESC)
Order of precedence in Arithmetic Expression: *,/
+, -

You can enforce priority by adding parentheses


Example:
SELECT Ename, SSN, Salary, 20* Salary/100 As percent increase,
, Salary+(20* Salary/100 ) As New Salary
FROM Employee;
ORDER BY SSN DESC, Salary ASC;
Arithmetic Expressions and Order by Clause
(ASC, DESC) (Cont.) Employee table

Example: SSN Ename Dnum Salary


100 Ahmed 2 5000
SELECT SSN, Ename, Salary, 200 Mai 2 8000
10* Salary/100 As Salary 300 Ali 2 4000
increase,
400 Mahmoud 3 10000
, Salary+(20* Salary/100 ) As
New Salary Output
FROM Employee; SSN Ename Salary Salary increase New Salary

ORDER BY SSN DESC; 400 Mahmoud 10000 1000 11000


300 Ali 4000 400 4400
200 Mai 8000 800 8800
100 Ahmed 5000 500 5500
1. Insert your personal data to the employee table as a new
employee in department number 30, SSN = 102672, INSERT INTO table_name
Superssn = 112233. (column1, column2, ...)
2. your salary has been upgraded by 20 present of its last VALUES (value1, value2, ...)
value. UPDATE table_name
3. If you know that the company policy is to pay an annual SET column_1= new value,
column_2= new value
commission for each employee with specific percent WHERE condition
equals 10% of his/her annual salary .Display each
employee full name and his annual commission in an SELECT <attribute list >
ANNUAL COMM column (alias). FROM <table>
WHERE <condition>
4. Display the employees Id, name who earns more than ORDER BY <attribute list >
10000 LE annually.
Solutions
1. Insert your personal data to the employee table as a new employee
in department number 30, SSN = 102672, Superssn = 112233.

Insert Into Employee(Fname, Lname, SSN, BDATE, Address, Sex,


Salary, Superssn, Dno) values('Reem', 'Mohamed', 102672,
'2/10/1990', '2 Gomhoria St. Mansoura', 'F', 1400, 112233, 30);
Solutions (Cont.)
2. your salary has been upgraded by 20 present of its last value.

Update Employee
SET salary= salary+salary*0.2
Where SSN= 102672;
Solutions (Cont.)
3. If you know that the company policy is to pay an annual commission
for each employee with specific percent equals 10% of his/her annual
salary .Display each employee full name and his annual commission in
an ANNUAL COMM column (alias).

SELECT Fname+' '+Lname As FullName ,(salary*12*0.1)As


[ANNUAL COMM ]
from Employee;
Solutions (Cont.)
4. Display the employees Id, name who earns more than 10000 LE
annually.

SELECT SSN, Fname, Lname


FROM Employee
Where salary*12>10000;
NoSQL Database Overview
What is NoSQL Database?
Why NoSQL Database?
When to avoid NoSQL Database?
MongoDB
What is NoSQL Database?

various approaches to classifying NoSQL databases


Column: Cassandra
Document: MongoDB , CouchDB
Key-value: FoundationDB
Graph: Neo4J
Why NoSQL Database?
High Data
Velocity

Data Big Data


Variety Volume
Data
Data
Complexity

Object-oriented programming that is easy to use and flexible


When to avoid NoSQL Database?

A lot of Transactions A lot of Relations


MongoDB
Open-source NoSQL database that provides high performance , high
availability ,and automatic scaling .
Document-oriented: MongoDB documents are similar to JSON
objects, called BSON.
The values of fields may include other documents, arrays, and arrays
of documents.
Great for unstructured data

A record in a MongoDB
SQL Vs MongoDB
Activities
Make a report (2-4 pages) with suitable illustrations on one of the
following topics
Evolution of Database Environment
Data warehousing
Business Intelligence
Discuss with illustration and suitable examples the following terms
Different types of joins
Union operators
Order by Clause
Exist Clause
Subqueries
References and Useful Links
Text book
R. Elmasr and S. B. Navathe, Database Systems, Sixth Edition, Pearson, 2010.
DBMS concepts
http://www.developer.com/db/article.php/719041/The-Elements-of-a-
Database.htm
https://www.tutorialspoint.com/dbms/dbms_overview.htm
Quizzes
https://quizlet.com/103479436/technology-in-action-chapter-11-flash-cards/
SQL tutorials
https://www.w3schools.com/sql/default.asp
https://www.techonthenet.com/sql/index.php
References and Useful Links (cont.)
Platform for online database schema generation
https://dashboard.genmymodel.com/
Microsoft Access Tutorials
https://www.gcflearnfree.org/access2016/
https://msdn.microsoft.com/en-us/library/bb243835(v=office.12).aspx
https://www.tutorialspoint.com/sql_certificate/using_ddl_statements.htm
https://www.gcflearnfree.org/access2010/introduction-to-databases/1/
MySQL DB
https://dev.mysql.com/downloads/installer/
NoSQL Databases
https://www.3pillarglobal.com/insights/exploring-the-different-types-of-nosql-databases
http://nosql-database.org/
MongoDB
https://www.mongodb.com/

S-ar putea să vă placă și