(IT) 08 Physical DM Dan Implementasi DB - DDL - DML

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

1

08 Physical Database Design,


DDL and DML
CT12F3 Database Modelling And Implementation
2

Learning Outcomes
Students can create design Physical Database
Students can explain impact of normalization and index for
database design
3

Topics
Introduction to Physical Database Design
Data Volumes and Usage Analysis
Designing Fields
Introduction to SQL
Data Definition Language
Data Manipulation Language
Data Control Language
VIew
4

Introduction to Physical
Database Design
5
Physical Database Design 1
 Purpose
• is to translate the logical description of data into the technical specifications for storing and retrieving data
 Goal
• The primary goal of physical database design is data processing efficiency
• to create a design for storing data that will provide adequate performance and ensure database integrity,
security, and recoverability
• to minimize the time required by users to interact with the information system
 Output
• Physical database design produces the technical specifications that programmers, database administrators,
and others involved in information systems construction will use during the implementation phase
 Scope in this course
• We concentrate in this chapter on the design of a single, centralized database especially in Selecting Data
Type.
• We concentrate on how to make processing of physical files and databases efficient, with less attention on
minimizing the use of space.
6
Physical Database Design 2
 Requirements
• Normalized relations, (number of rows in each table)
• Definitions of each attribute
• Descriptions of where and when data are used in various ways
• Expectations or requirements for response time and data security, backup, recovery, retention, and integrity
• Descriptions of the technologies
 Decisions
• Choosing the storage format (called data type)
• DBMS guidance regarding how to group attributes from the logical data model into physical records
• DBMS guidance regarding how to arrange similarly structured records in secondary memory (primarily
hard disks)
• Selecting structures (including indexes and the overall database architecture)
• Preparing strategies for handling queries against the database that will optimize performance and take
advantage of the file organizations and indexes that you have specified
7

Data Volumes and Usage


Analysis
8
Background
• Utility
• Important inputs to the physical database design process
• Benefit
• to maintain a good understanding of the size and usage patterns of the database throughout its life
cycle
9
Example
• Shows the ER diagram (without attributes) for a
simple inventory database for Pine Valley
Furniture Company.
• There are 3,000 PARTs in this database.
• The supertype PART has two subtypes,
MANUFACTURED (40% of all PARTs are
manufactured) and PURCHASED (70% are
purchased; because some PARTs are of both
subtypes, the percentages sum to more than
100%).
• The analysts at Pine Valley estimate that there are
typically 150 SUPPLIERs, and Pine Valley
receives, on average, 40 SUPPLIES instances
from each SUPPLIER, yielding a total of 6,000
SUPPLIES. The dashed arrows represent access
frequencies.
10
Example (cont)
• So, for example, across all applications that use this database, there are on average
20,000 accesses per hour of PART data, and these yield, based on subtype
percentages, 14,000 accesses per hour to PURCHASED PART data.
• There are an additional 6,000 direct accesses to PURCHASED PART data. Of
this total of 20,000 accesses to PURCHASED PART, 8,000 accesses then also
require SUPPLIES data and of these 8,000 accesses to SUPPLIES, there are
7,000 subsequent accesses to SUPPLIER data.
• For online and Web-based applications, usage maps should show the accesses per
second. Several usage maps may be needed to show vastly different usage patterns
for different times of day. Performance will also be affected by network
specifications.
• It can be helpful for subsequent physical database design steps if you can also
explain the nature of the access for the access paths shown by the dashed lines
11

Designing Fields
12
Background
• A field is the smallest unit of application data recognized by system software
• Field: simple attribute (single component)
• Specifications each field concern:
• Type of data
• Data integrity
• Mechanism to handle missing values
13
What is Data type?
• A data type is a detailed coding scheme recognized by system software, such as a
DBMS, for representing organizational data.
• The bit pattern of the coding scheme is usually transparent to you, but the space to
store data and the speed required to access data are of consequence in physical
database design.
• In this course, we will use the Oracle Data types
14
Why We Should Selecting Data types?
• Selecting a data type involves four objectives that will have
different relative levels of importance for different
applications:
1. Represent all possible values.
2. Improve data integrity.
3. Support all data manipulations.
4. Minimize storage space.
15
Selecting Data types..
• An optimal data type for a field can, in minimal space, represent every
possible value (while eliminating illegal values) for the associated
attribute and can support the required data manipulation (e.g., numeric
data types for arithmetic operations and character data types for string
manipulation).
• Any attribute domain constraints from the conceptual data model are
helpful in selecting a good data type for that attribute.
16
Introduction to Oracle Data types
Each column value and constant in a SQL statement has a data type, which is
associated with a specific storage format, constraints, and a valid range of values.
When you create a table, you must specify a data type for each of its columns.

p e s …
ata ty
o f D
p le
E xa m
17
CHAR Data type
• The CHAR data type stores fixed-length character strings.
• When you create a table with a CHAR column, you must specify a string length (in
bytes or characters) between 1 and 2000 bytes for the CHAR column width.
• The default is 1 byte.
• Oracle then guarantees that:
• When you insert or update a row in the table, the value for the CHAR column has the fixed
length.
• If you give a shorter value, then the value is blank-padded to the fixed length.
• If a value is too large, Oracle Database returns an error.
18
VARCHAR2 and VARCHAR Data types
• The VARCHAR2 data type stores variable-length character strings.
• When you create a table with a VARCHAR2 column, you specify a maximum string length (in bytes
or characters) between 1 and 4000 bytes for the VARCHAR2 column.
• For each row, Oracle Database stores each value in the column as a variable-length field unless a
value exceeds the column's maximum length, in which case Oracle Database returns an error.
• Using VARCHAR2 and VARCHAR saves on space used by the table.
For example, assume you declare a column VARCHAR2 with a maximum size of 50 characters. In
a single-byte character set, if only 10 characters are given for the VARCHAR2 column value in a
particular row, the column in the row's row piece stores only the 10 characters (10 bytes), not 50.
• The VARCHAR data type is synonymous with the VARCHAR2 data type. To avoid possible
changes in behavior, always use the VARCHAR2 data type to store variable-length character
strings.
19
Overview of Numeric Data types
• The numeric data types store positive and negative fixed and
floating-point numbers, zero, infinity, and values that are the
undefined result of an operation (that is, is "not a number" or
NAN).
• This section includes the following topics:
• NUMBER Datatype
• Floating-Point Numbers
20
NUMBER Data type
• The NUMBER data type stores fixed and floating-point numbers.
• The following numbers can be stored in a NUMBER column:
• Positive numbers in the range 1 x 10-130 to 9.99...9 x 10125 with up to 38 significant digits
• Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with up to 38 significant digits
• Zero
• Positive and negative infinity (generated only by importing from an Oracle Database, Version 5)
21
Specifying The Numeric Columns
• For numeric columns, you can specify the column as:

• Optionally, you can also specify a precision (total number of digits) and scale
(number of digits to the right of the decimal point).

• If a precision is not specified, the column stores values as given. If no scale is


specified, the scale is zero.
22
Specifying The Numeric Columns(cont.)
• Oracle guarantees portability of numbers with a precision equal to or less than 38 digits. You can
specify a scale and no precision:

• In this case, the precision is 38, and the specified scale is maintained.
• When you specify numeric fields, it is a good idea to specify the precision and scale. This
provides extra integrity checking on input.
• For input and output of numbers, the standard Oracle Database default decimal character is a period,
as in the number 1234.56. The decimal is the character that separates the integer and decimal parts
of a number. You can change the default decimal character with the initialization parameter
NLS_NUMERIC_CHARACTERS. You can also change it for the duration of a session with the
ALTER SESSION statement. To enter numbers that do not use the current default decimal character,
use the TO_NUMBER function.
23

How Scale Factors Affect Numeric Data Storage?


24
Overview of DATE Data type
• The DATE data type stores point-in-time values (dates and times) in a table. The
DATE data type stores the year (including the century), the month, the day, the
hours, the minutes, and the seconds (after midnight).

• Oracle Database uses its own internal format to store dates. Date data is stored in
fixed-length fields of seven bytes each, corresponding to century, year, month, day,
hour, minute, and second
25
Formatting DATE Data type
• For input and output of dates, the standard Oracle date format is DD-MON-YY, as follows:

• You can change this default date format for an instance with the parameter NLS_DATE_FORMAT.
You can also change it during a user session with the ALTER SESSION statement. To enter dates
that are not in standard Oracle date format, use the TO_DATE function with a format mask:

• Oracle Database stores time in 24-hour format—HH:MI:SS. By default, the time in a date field is
00:00:00 A.M. (midnight) if no time portion is entered. In a time-only entry, the date portion
defaults to the first day of the current month. To enter the time portion of a date, use the TO_DATE
function with a format mask indicating the time portion, as in:
26

Introduction to SQL
27
Overview SQL
• SQL ( Structured Query Language) is nonprocedural language that provides
database access. It is nonprocedural in that users describe in SQL what they want
done, and the SQL language compiler automatically generates a procedure to
navigate the database and perform the desired task.
• Oracle SQL includes many extensions to the ANSI/ISO standard SQL language,
and Oracle tools and applications provide additional statements. The Oracle tools
SQL*Plus and Oracle Enterprise Manager let you run any ANSI/ISO standard SQL
statement against an Oracle database, as well as additional statements or functions
that are available for those tools.
• Although some Oracle tools and applications simplify or mask SQL use, all
database operations are performed using SQL. Any other data access method
circumvents the security built into Oracle Database and potentially compromises
data security and integrity
28
SQL Statements
• All operations performed on the information in Oracle Database are run using SQL
statements.
• A statement consists of identifiers, parameters, variables, names, datatypes, and
SQL reserved words.
• SQL reserved words have special meaning in SQL and cannot be used for any other
purpose. For example, SELECT and UPDATE are reserved words and cannot be
used as table names.
29
Types of SQL Command
30

Data Definition Language


( DDL)
31
Overview DDL

• These commands are used to create, alter, and drop tables, views, and indexes.
• There may be other objects controlled by the DDL, depending on the DBMS. For
example, many DBMSs support defining synonyms (abbreviations) for database
objects or a field to hold a specified sequence of numbers (which can be helpful in
assigning primary keys to rows in tables).
• In a production database, the ability to use DDL commands will generally be
restricted to one or more database administrators in order to protect the database
structure from unexpected and unapproved changes.
• In development or student databases, DDL privileges will be granted to more users.
32
Create Table
• We create tables from the Relational Scheme.
• Steps :
1. Create Tables that does not refer to other tables (i.e no Foreign key)
2. Add primary key constraints
3. Add other constraints (i.e unique constraints)
4. Create the rest of tables from the Relational Scheme
5. Add foreign key constraints
33
Create Table Script
Create Table Script 1 Create Table Script 2

CREATE TABLE Table_name CREATE TABLE Table_name


(Column_name_1 data_type [PRIMARY KEY], (Column_name_1 data_type,
Column_name_2 data_type, Column_name_2 data_type,
……. …….
Column_name_n data_type); Column_name_n data_type,
[CONSTRAINTS constraint_name_PK PRIMARY KEY (column_name) ] );
34
Alter Table Script
This script can be used to add / subtract /
modify fields, as well as add / drop constraints AlterTable Script 2

on the Table (Add/ Drop PRIMARY KEY constraint)

Alter Table Script 1


ALTER TABLE Table_name
(Add/Drop/Modify Column)
ADD CONSTRAINTS constraint_name _PK PRIMARY KEY(Column_name);

ALTER TABLE Table_name


ALTER TABLE Table_name
ADD (
DROP CONSTRAINTS constraint_name_PK;
New_column_name1 data_type,
New_column_name2 data_type );
Alter Table Script 13

ALTER TABLE Table_name (Add/ Drop FOREIGN KEY constraint)

MODIFY (
Column_name1 new_data_type, ALTER TABLE Table_name

Column_name2 new_data_type ); ADD CONSTRAINTS FK_constraint_name FOREIGN KEY (Column_name)


REFERENCES Ref_table_name(ref_column_name);

ALTER TABLE Table_name


ALTER TABLE Table_name
DROP COLUMN Column_name1;
DROP CONSTRAINTS FK_constraint_name;
35
Create Tables (by example)
• CREATE TABLE Patient
Patient Physician Treatment (PatientID char(5) PRIMARY KEY,
PatientName varchar(30));
PK PatientID PK PhysicianID PK TreatmentCode
• CREATE TABLE Physician
PatientName PhysicianName TreatmentDescription (………………………………………..);

• CREATE TABLE Treatment


(………………………………………..);

• CREATE TABLE PatientTreatment


PatientTreatment (PTreatmentID char(7) PRIMARY KEY,
PatientID char(5),
PK PTreatmentID
PhysicianID char(5),
TreatmentCode char(5),
FK PatientID
PTreatmentDate DATE,
FK PhysicianID PTreatmentTime TIMESTAMP,
PTreatmentResult varchar (50),
FK TreatmentCode CONSTRAINT FK_PatientID FOREIGN KEY (PatientID)
REFERENCES Patient(PatientID),
PTreatmentDate
CONSTRAINT FK_PhysicianID FOREIGN KEY (PhysicianID)
REFERENCES Physician(PhysicianID),
PtreatmentTime
………………………………………………………………………..);
PTreatmentResult
36
DROP & PURGE
 Use the DROP TABLE statement to remove a table or object table to the recycle bin or to remove the table and
all its data from the database entirely.
 Specify PURGE if you want to drop the table and release the space associated with it in a single step. If you
specify PURGE, then the database does not place the table and its dependent objects into the recycle bin.
 Unless you specify the PURGE clause, the DROP TABLE statement does not result in space being released
back to the tablespace for use by other objects, and the space continues to count toward the user's space quota.
 You cannot roll back a DROP TABLE statement
37
TRUNCATE Table
 Use the TRUNCATE TABLE statement to remove all rows from a table.
 You cannot roll back a TRUNCATE TABLE statement
 This statement is subject to the following restrictions:
• You cannot individually truncate a table that is part of a cluster. You must either truncate the cluster, delete
all rows from the table, or drop and re-create the table.
• You cannot truncate the parent table of an enabled foreign key constraint. You must disable the constraint
before truncating the table. An exception is that you can truncate the table if the integrity constraint is self-
referential.
• If a domain index is defined on table, then neither the index nor any index partitions can be marked
IN_PROGRESS.
• You cannot truncate the parent table of a reference-partitioned table. You must first drop the reference-
partitioned child table.
38

CT12F3 DATABASE MODELLING AND


IMPLEMENTATION

VIEW
Intro to View
Maxmanroe.com

Image Designed by stories / Freepik


Intro to View 39

• View is a mechanism to refer or hide certain column or data of database


table
• There are 2 kinds of view:
• Dynamic view
• Materialized view
40

CT12F3 DATABASE MODELLING AND


IMPLEMENTATION

VIEW
Dynamic View
Maxmanroe.com

Image Designed by stories / Freepik


Dynamic View 41

• Dynamic view is a virtual table that is created dynamically upon request


by user
• Dynamic view is not a temporary table. Rather, its definition is stored in
the system catalog, and the contents of the view are materialized as a
result of an SQL query that uses the view
• The data result of dynamic view is not maintained as real data
Dynamic View 42

• To create dynamic view, we use command:


CREATE VIEW v AS <query expression>
where:
• <query expression> is any legal expression, that will become the view definition
• v represents the view name

• Example:
CREATE VIEW OutstandingStudent AS
SELECT NAME, COURSE, GRADE
FROM Student
WHERE GRADE > B
Dynamic View 43

• After view OutstandingStudent is created, we can use this view in query


like usual table:
SELECT * FROM OutstandingStudent

• The result of query above will be the same like when we execute the
query expression we define for the view:
SELECT NAME, COURSE, GRADE
FROM Student
WHERE GRADE > B
Dynamic View Pros 44

• Simplify query commands


• Help provide data security and confidentiality
• Improve programmer productivity
• Contain most up to date table data
• Use little storage space
• Provide a customized view for a user
• Establish physical data independence
Dynamic View Cons 45

• Costly usage and time of processing, because its contents must be


calculated each time they are requested (that is, each time the view is
used in a query)
• If a table’s structure is changed, and that structure is referenced in view
definition, view must be recreated to prevent query error
46

CT12F3 DATABASE MODELLING AND


IMPLEMENTATION

VIEW
Materialized View
Maxmanroe.com

Image Designed by stories / Freepik


Materialized View 47

• Materialized view is a table that contains copies or replicas of data,


based on SQL queries created in the same manner as dynamic view.
• Because materialized view is not a virtual table, the data must be
maintained to keep it synchronized with its referenced tables
• Synchronizing data is done with predetermined time interval or events,
or triggered (i.e. when the table needs to be accessed)
Materialized View 48

• To create materialized view, we use command:


CREATE TABLE t AS (<query expression>)
where:
• <query expression> is any legal expression, that will become the table structure
• t represents the table name

• Example:
CREATE TABLE OutstandingStudent AS
(SELECT NAME, COURSE, GRADE
FROM Student
WHERE GRADE > B)
Materialized View 49

• Table OutstandingStudent will be created with all data from query


expression result included in it
Materialized View Pros 50

• Simplify query commands


• Help provide data security and confidentiality
• Improve programmer productivity
• Provide a customized view for a user
• Establish physical data independence
• May improve the performance of distributed queries, especially if the
data in the materialized view are relatively static and do not have to be
refreshed very often
Materialized View Cons 51

• May not contain the most up to date table data


• Use more storage space than dynamic view
• Data must be maintained properly
52

CT12F3 DATABASE MODELLING AND


IMPLEMENTATION

VIEW
Examples
Maxmanroe.com

Image Designed by stories / Freepik


Example 1 53

CREATE VIEW ExpensiveStuff_V AS


SELECT ProductID, ProductDescription, ProductStandardPrice
FROM Product_T
WHERE ProductStandardPrice > 300
Example 2 54

CREATE VIEW OrderTotals_V AS


SELECT ProductID Product,
SUM (ProductStandardPrice*OrderedQuantity) Total
FROM Invoice_V
GROUP BY ProductID
55

Data Manipulation
Language
(DML)
56
OVERVIEW DML
• Many consider the DML commands to be the core commands of SQL.
• These commands are used for updating, inserting, modifying, and querying the data
in the database.
• They may be issued interactively, so that a result is returned immediately following
the execution of the statement, or they may be included within programs written in
a procedural programming language, such as C, Java, PHP, or COBOL, or with a
GUI tool (e.g., Oracle’s SQL Developer, SQL Assistant with Teradata, or MySQL
Query Browser).
 Use command "COMMIT" to change data permanently to the database
 You can use “ROLLBACK” to cancel the change of data
57
INSERT
 Use the INSERT statement to add rows to a table.
 Use command "COMMIT" to change data permanently to the database

INSERT Script 1 INSERT Script 2


(with specified column) (with all column)

INSERT INTO Table_name INSERT INTO Table_name


(column1, column2,…) VALUES
VALUES (expression1, expression2, …);
(expression1, expression2, …);
58
INSERT ( By Example)

SQL SCRIPT

INSERT INTO Category


(category_id, category_name)
Values
(150, “Miscellaneous”)
OR
INSERT INTO Category
Values
(150, “Miscellaneous”)
59
UPDATE
 Use the UPDATE statement to change existing values in a table
 Use command "COMMIT" to change data permanently to the database

UPDATE Table_name
SET Column_name = expression_value
[WHERE] Condition;
60
UPDATE ( By Example)

SQL SCRIPT

UPDATE Category
SET category_name = “Marketing”
WHERE category_id = 150;

Marketing
61
DELETE
• Use the DELETE statement to remove rows
• Use command "COMMIT" to change data permanently to the database

DELETE FROM Table_name


[WHERE] Condition;
62
DELETE ( By Example)

SQL SCRIPT

DELETE FROM Category


WHERE category_id = 150;
63

Data Control Language


(DCL)
64
OVERVIEW DCL
• These commands help a DBA control the database;
• They include commands to grant or revoke privileges to access the database or
particular objects within the database and to store or remove transactions that would
affect the database.
65
GRANT, REVOKE
• Use the GRANT statement to grant:
• System privileges to users and roles.
• Roles to users and roles.
• Object privileges for a particular object to users, roles, and PUBLIC. Table 18-2 lists object
privileges and the operations that they authorize.

• Use the REVOKE statement to:


• Revoke system privileges from users and roles
• Revoke roles from users and roles
• Revoke object privileges for a particular object from users and roles
66
GRANT, REVOKE (By Example)

Granting a System Privilege to a User: Example Revoking a System Privilege from a User: Example

Granting System Privileges to a Role: Example Revoking a Role from a User: Example

Revoking a System Privilege from a Role: Example


67

Reference

Hoffer, Jeffrey A., et.al., "Modern Database Management", Twelfth Edition, Pearson,
2016. Chapter 5
https://docs.oracle.com
68
Questions

You might also like