Sunteți pe pagina 1din 23

Prepared By : Tariq Zaman

Email ID : adbms2019@gmail.com

Version 0.3
Lecture 1: Intro
Lecture 2: Review of Basic Concepts (Database Development, Database Administration,
Application Program Development, Schema Objects, SQL, PL/SQL, SQL Plus)

 Database development

A core aspect of software engineering is the subdivision of the development process into a
series of phases, or steps, each of which focuses on one aspect of the development. The
collection of these steps is sometimes referred to as the software development life cycle (SDLC).
The software product moves through this life cycle (sometimes repeatedly as it is refined or
redeveloped) until it is finally retired from use. Ideally, each phase in the life cycle can be
checked for correctness before moving on to the next phase.

Software Development Life Cycle – Waterfall

This waterfall figure, seen in Figure 13.1, illustrates a general waterfall model that could apply
to any computer system development. It shows the process as a strict sequence of steps where
the output of one step is the input to the next and all of one step has to be completed before
moving onto the next.

Figure 13.1. Waterfall model.

We can use the waterfall process as a means of identifying the tasks that are required, together
with the input and output for each activity. What is important is the scope of the activities,
which can be summarized as follows:

 Establishing requirements involves consultation with, and agreement among, stakeholders about what
they want from a system, expressed as a statement of requirements.
 Analysis starts by considering the statement of requirements and finishes by producing a system
specification. The specification is a formal representation of what a system should do, expressed in
terms that are independent of how it may be realized.
 Design begins with a system specification, produces design documents and provides a detailed
description of how a system should be constructed.
 Implementation is the construction of a computer system according to a given design document and
taking into account the environment in which the system will be operating (e.g., specific hardware or
software available for the development). Implementation may be staged, usually with an initial system
that can be validated and tested before a final system is released for use.
 Testing compares the implemented system against the design documents and requirements
specification and produces an acceptance report or, more usually, a list of errors and bugs that require a
review of the analysis, design and implementation processes to correct (testing is usually the task that
leads to the waterfall model iterating through the life cycle).
 Maintenance involves dealing with changes in the requirements or the implementation environment,
bug fixing or porting of the system to new environments (e.g., migrating a system from a standalone PC
to a UNIX workstation or a networked environment). Since maintenance involves the analysis of the
changes required, design of a solution, implementation and testing of that solution over the lifetime of a
maintained software system, the waterfall life cycle will be repeatedly revisited.

Database Design Life Cycle

Database Design process is a series of steps used to properly design a database system.

And this is used to map the conceptual model to implementation model. Database
development team (DBA, Developer and programmers) uses these steps to design and
implement a database system.

We can use the waterfall cycle as the basis for a model of database development.
Figure 13.2. A waterfall model of the activities and their outputs for database development.

Using these assumptions and Figure 13.2, we can see that this diagram represents a model of
the activities and their outputs for database development. It is applicable to any class of DBMS,
not just a relational approach.

Database application development is the process of obtaining real-world requirements,


analyzing requirements, designing the data and functions of the system, and then
implementing the operations in the system.

Requirements Gathering / Planning

The first step is requirements gathering. During this step, the database designers have to
interview the customers (database users) to understand the proposed system and obtain and
document the data and functional requirements. The result of this step is a document that
includes the detailed requirements provided by the users.

The data requirements document is used to confirm the understanding of requirements with
users. The requirements should not describe how the data is to be processed, but rather what
the data items are, what attributes they have, what constraints apply and the relationships that
hold between the data items.

Analysis

Data analysis begins with the statement of data requirements and then produces a conceptual
data model. The aim of analysis is to obtain a detailed description of the data that will suit user
requirements so that both high and low level properties of data and their use are dealt with.
These include properties such as the possible range of values that can be permitted for
attributes (e.g., in the school database example, the student course code, course title and
credit points).

The conceptual data model then is a formal representation of what data a database should
contain and the constraints the data must satisfy. This should be expressed in terms that are
independent of how the model may be implemented. As a result, analysis focuses on the
questions, “What is required?” not “How is it achieved?”

Logical Design

Database design starts with a conceptual data model and produces a specification of a logical
schema; this will determine the specific type of database system (network, relational, object-
oriented) that is required. The relational representation is still independent of any specific
DBMS; it is another conceptual data model.

We can use a relational representation of the conceptual data model as input to the logical
design process. The output of this stage is a detailed relational specification, the logical schema,
of all the tables and constraints needed to satisfy the description of the data in the conceptual
data model. It is during this design activity that choices are made as to which tables are most
appropriate for representing the data in a database. These choices must take into account
various design criteria including, for example, flexibility for change, control of duplication and
how best to represent the constraints. It is the tables defined by the logical schema that
determine what data are stored and how they may be manipulated in the database.

Figure 13.3 summarizes the iterative (repeated) steps involved in database design, based on the
overview given. Its main purpose is to distinguish the general issue of what tables should be
used from the detailed definition of the constituent parts of each table – these tables are
considered one at a time, although they are not independent of each other. Each iteration that
involves a revision of the tables would lead to a new design; collectively they are usually
referred to as second-cut designs, even if the process iterates for more than a single loop.
Figure 13.3. A summary of the
iterative steps involved in database design.

At the end of our design stage, the logical schema will be specified by SQL data definition
language (DDL) statements, which describe the database that needs to be implemented to
meet the user requirements.

Implementation

Implementation involves the construction of a database according to the specification of a


logical schema. This will include the specification of an appropriate storage schema, security
enforcement, external schema and so on. Implementation is heavily influenced by the choice of
available DBMSs, database tools and operating environment. There are additional tasks beyond
simply creating a database schema and implementing the constraints – data must be entered
into the tables, issues relating to the users and user processes need to be addressed, and the
management activities associated with wider aspects of corporate data management need to
be supported. In keeping with the DBMS approach, we want as many of these concerns as
possible to be addressed within the DBMS. We look at some of these concerns briefly now.

In practice, implementation of the logical schema in a given DBMS requires a very detailed
knowledge of the specific features and facilities that the DBMS has to offer. In an ideal world,
and in keeping with good software engineering practice, the first stage of implementation
would involve matching the design requirements with the best available implementing tools
and then using those tools for the implementation. In database terms, this might involve
choosing vendor products with DBMS and SQL variants most suited to the database we need to
implement. However, we don’t live in an ideal world and more often than not, hardware choice
and decisions regarding the DBMS will have been made well in advance of consideration of the
database design. Consequently, implementation can involve additional flexing of the design to
overcome any software or hardware limitations.

Realizing the Design

After the logical design has been created, we need our database to be created according to the
definitions we have produced. This will probably involve the use of SQL to create tables and
constraints that satisfy the logical schema description and the choice of appropriate storage
schema (if the DBMS permits that level of control).

One way to achieve this is to write the appropriate SQL DDL statements into a file that can be
executed by a DBMS so that there is an independent record, a text file, of the SQL statements
defining the database. Another method is to work interactively using a database tool like SQL
Server Management Studio or Microsoft Access. Whatever mechanism is used to implement
the logical schema, the result is that a database, with tables and constraints, is defined but will
contain no data for the user processes.

Populating the Database

After a database has been created, there are two ways of populating the tables – either from
existing data or through the use of the user applications developed for the database.

For some tables, there may be existing data from another database or data files. For example,
in establishing a database for a hospital, you would expect that there are already some records
of all the staff that have to be included in the database. Data might also be brought in from an
outside agency (address lists are frequently brought in from external companies) or produced
during a large data entry task (converting hard-copy manual records into computer files can be
done by a data entry agency). In such situations, the simplest approach to populate the
database is to use the import and export facilities found in the DBMS.

Facilities to import and export data in various standard formats are usually available (these
functions are also known in some systems as loading and unloading data). Importing enables a
file of data to be copied directly into a table. When data are held in a file format that is not
appropriate for using the import function, then it is necessary to prepare an application
program that reads in the old data, transforms them as necessary and then inserts them into
the database using SQL code specifically produced for that purpose. The transfer of large
quantities of existing data into a database is referred to as a bulk load. Bulk loading of data may
involve very large quantities of data being loaded, one table at a time so you may find that
there are DBMS facilities to postpone constraint checking until the end of the bulk loading.
 Database Administration:

Database administration enables you to help companies create new or update existing databases
based on their internal data collection needs.

Databases are common to most modern businesses. There isn't anything on the Internet without a
database. Technology is always growing and companies in all industries around the globe need database
administrators (DBAs) to make sure all information stored on their computers is secure and only
available to authorized users.

Armed with the knowledge and experience to write and install computer programs and debug software
issues, database administrators are the people who help companies of any size set up, maintain, and
secure large volumes of information.

What Does a Database Administrator Do?

Technological advancements and the ability to store mind-boggling amounts of data on drives and in the
cloud to run e-commerce is driving the increased need for database administrators. Particular specialties
that use database administration skills include System DBA and Application DBA.

 System DBAs, also referred to as traditional or general-purpose DBAs, generally focus on any
physical and technical aspects of database management that keep systems running smoothly,
efficiently and error-free.

A system DBA responsibilities can include the following tasks:

 Installing and upgrading the Database server and application tools


 Allocating system storage and planning future storage requirements for the database system
 Creating primary database storage structures (tablespaces) after application developers have
designed an application
 Creating primary objects (tables, views, indexes) once application developers have designed an
application
 Modifying the database structure, as necessary, from information given by application
developers
 Enrolling users and maintaining system security
 Ensuring compliance with Oracle license agreements
 Controlling and monitoring user access to the database
 Monitoring and optimizing the performance of the database
 Planning for backup and recovery of database information
 Maintaining archived data on tape
 Backing up and restoring the database

 Application DBAs are experienced system DBAs with specialized skills for a particular application
or set of applications, such as database design, functional expertise or particular server
knowledge, such as Oracle, or a particular suite of Oracle applications.
Their responsibilities include the following tasks:

 Designing and developing the database application


 Designing the database structure for an application
 Estimating storage requirements for an application
 Specifying modifications of the database structure for an application
 Relaying this information to a database administrator
 Tuning the application during development
 Establishing security measures for an application during development

 Schema:

A database schema represents the logical configuration of all or part of a relational database. It
can exist both as a visual representation and as a set of formulas known as integrity constraints
that govern a database. These formulas are expressed in a data definition language, such as
SQL. As part of a data dictionary, a database schema indicates how the entities that make up
the database relate to one another, including tables, views, stored procedures, and more.

Typically, a database designer creates a database schema to help programmers whose software
will interact with the database. The process of creating a database schema is called data
modeling. When following the three-schema approach to database design, this step would
follow the creation of a conceptual schema. Conceptual schemas focus on an organization’s
informational needs rather than the structure of a database.

There are two main kinds of database schema:


1. A logical database schema conveys the logical constraints that apply to the stored data. It
may define integrity constraints, views, and tables.
2. A physical database schema lays out how data is stored physically on a storage system in
terms of files and indices.

Data Dictionary:

A data dictionary is a file or a set of files that contains a database's metadata. The data
dictionary contains records about other objects in the database, such as data ownership,
data relationships to other objects, and other data.

The data dictionary is a crucial component of any relational database. Ironically, because of
its importance, it is invisible to most database users. Typically, only database administrators
interact with the data dictionary.

 SQL and PL/SQL:

SQL is a Structured Query Language used to PL-SQL is a programming language SQL, used to write
issue a single query or execute a single full programs using variables, loops, operators etc. to
insert/update/delete. carry out multiple selects/inserts/updates/deletes.

SQL may be considered as the source of data PL/SQL can be considered as the application language
for our reports, web pages and screens. similar to Java or PHP. It might be the language used to
build, format and display those reports, web pages and
screens.

SQL is a data oriented language used to select PL/SQL is a procedural language used to create
and manipulate sets of data. applications.

SQL is used to write queries, DDL (Data PL/SQL is used to write program blocks, functions,
Definition Language) and DML (Data procedures triggers, and packages.
Manipulation Language) statements.

SQL is executed one statement at a time. PL/SQL is executed as a block of code.

SQL is declarative, i.e., it tells the database Whereas, PL/SQL is procedural, i.e., it tells the
what to do but not how to do it. database how to do things.
SQL can be embedded within a PL/SQL But PL/SQL can’t be embedded within a SQL statement.
program.

 SQL Plus:

SQL*Plus is an interactive and batch query tool that is installed with every Oracle Database
Server or Client installation. It has a command-line user interface, a Windows Graphical User
Interface (GUI) and the iSQL*Plus web-based user interface.

SQL*Plus has its own commands and environment, and it provides access to the Oracle
Database. It enables you to enter and execute SQL, PL/SQL, SQL*Plus and operating system
commands to perform the following:

 Format, perform calculations on, store, and print from query results
 Examine table and object definitions
 Develop and run batch scripts
 Perform database administration

Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of
information.
o Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the
database.

Types of Integrity Constraint


1. Domain constraints

o Domain constraints can be defined as the definition of a valid set of values for an
attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc.
The value of the attribute must be available in the corresponding domain.

Example:

2. Entity integrity constraints


o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.

Example:
3. Referential Integrity Constraints
o A referential integrity constraint is specified between two tables.
o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.

Example:

4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.

Example:
 Transaction Processing
Lecture 03:  Create Table, Alter Table, Drop Table, Applying and Removing Constraints (Primary Key,
Unique, Not Null, Foreign Key, Check)
 Assignment 1

 Transaction Processing:

Definition 1: A transaction is a way of representing a state change.

Definition 2: A transaction can be defined as a group of tasks. A single task is the minimum
processing unit which cannot be divided further.
Transactions ideally have four properties, commonly known as ACID:

 Atomicity (if the change is committed, it happens in one fell swoop; you can never see
"half a change")
OR
 This property states that a transaction must be treated as an atomic unit, that is, either
all of its operations are executed or none. There must be no state in a database where a
transaction is left partially completed. States should be defined either before the
execution of the transaction or after the execution/abortion/failure of the transaction.

 Consistent (the change can only happen if the new state of the system will be valid; any
attempt to commit an invalid change will fail, leaving the system in its previous valid state)
OR

 The database must remain in a consistent state after any transaction. No transaction
should have any adverse effect on the data residing in the database. If the database was
in a consistent state before the execution of a transaction, it must remain consistent
after the execution of the transaction as well.

 Isolated (no-one else sees any part of the transaction until it's committed)
OR
 The database should be durable enough to hold all its latest updates even if the system
fails or restarts. If a transaction updates a chunk of data in a database and commits,
then the database will hold the modified data. If a transaction commits but the system
fails before the data could be written on to the disk, then that data will be updated once
the system springs back into action.
 Durable (once the change has happened - if the system says the transaction has been
committed, the client doesn't need to worry about "flushing" the system to make the
change "stick")
OR
 In a database system where more than one transaction are being executed
simultaneously and in parallel, the property of isolation states that all the transactions
will be carried out and executed as if it is the only transaction in the system. No
transaction will affect the existence of any other transaction.
 Table:
In relational databases, and flat file databases, a table is a set of data elements (values) using a
model of vertical columns (identifiable by name) and horizontal rows, the cell being the unit
where a row and column intersect.[1] A table has a specified number of columns, but can have
any number of rows.[2] Each row is identified by one or more values appearing in a particular
column subset.

1) Create

The CREATE TABLE statement is used to create a new table in a database.

Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).

Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
2) Alter

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
ALTER TABLE table_name
ADD column_name datatype;
Example
Alter TABLE Persons
ADD Country varchar(20);
OR
Alter TABLE Persons
DROP Country varchar(20);

3) Drop

The DROP TABLE statement is used to drop an existing table in a database.


Syntax
DROP TABLE table_name;

4) Applying and Removing Constraints

Constraints are used to specify rules for data in a table. Constraints can be specified when the table is
created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE
statement.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

Examples:

i) Not Null
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
ii) Unique
iii) Primary Key
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
OR
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
iv) Foreign Key
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
OR
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
v) Check
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
vi) Default
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
vii) Index
CREATE INDEX idx_lastname
ON Persons (LastName);
Lecture 04:  View, type of views, Creating Simple Views, Read Only Option, With Check Option,
Complex Views

Views

A view is a virtual table based on the result-set of an SQL statement.

OR

A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.

A view can contain all rows of a table or select rows from a table. A view can be created from
one or many tables which depends on the written SQL query to create a view.

Views, which are a type of virtual tables allow users to do the following −

 Structure data in a way that users or classes of users find natural or intuitive.

 Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.

 Summarize data from various tables which can be used to generate reports.

 To create a view, a user must have the appropriate system privilege according to the
specific implementation.
Types of Views:
There are 2 types of Views in SQL: 1) Simple View 2)Complex View.
Simple views can only contain a single base table.
Complex views can be constructed on more than one base table. In particular, complex
views can contain: join conditions, a group by clause, a order by clause.
The key differences between these types of Views are:

SIMPLE VIEW COMPLEX VIEW

Contains only one single base table or is Contains more than one base tables or is

created from only one table. created from more than one tables.
We cannot use group functions like

MAX(), COUNT(), etc. We can use group functions.

Does not contain groups of data. It can contain groups of data.

DML operations could be performed DML operations could not always be

through a simple view. performed through a complex view.

INSERT, DELETE and UPDATE are directly We cannot apply INSERT, DELETE and UPDATE

possible on a simple view. on complex view directly.

Basic view Creation:


The basic CREATE VIEW syntax is as follows −

 CREATE VIEW view_name AS


 SELECT column1, column2.....
 FROM table_name
 WHERE [condition];

Example 1:

CREATE VIEW CUSTOMERS_VIEW AS

SELECT name, age

FROM CUSTOMERS;

Example 2

CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL;
Update a View
Values in a view can be updated which will ultimately updated in base table. Update takes place
based on rule/condition that must be fulfilled. Else update will not be executed.

 All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
 UPDATE CUSTOMERS_VIEW
 SET AGE = 35
 WHERE name = 'Ramesh';

Inserting Rows into a View


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.

Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the
NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as you
insert them in a table.

INSERT INTO VW_STUDENT


SELECT 1,'Peter','Parker' UNION;

Deleting Rows into a View


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.

Following is an example to delete a record having AGE = 22.

DELETE FROM CUSTOMERS_VIEW

WHERE age = 22;

Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple and is given below −

DROP VIEW view_name;


Rules for Update/Insert into a View
A view can be updated under certain conditions which are given below −

 The SELECT clause may not contain the keyword DISTINCT.

 The SELECT clause may not contain summary functions.

 The SELECT clause may not contain set functions.

 The SELECT clause may not contain set operators.

 The SELECT clause may not contain an ORDER BY clause.

 The FROM clause may not contain multiple tables.

 The WHERE clause may not contain subqueries.

 The query may not contain GROUP BY or HAVING.

 Calculated columns may not be updated.

The WITH CHECK OPTION


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK
OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view definition.

If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.

The following code block has an example of creating same view CUSTOMERS_VIEW with the
WITH CHECK OPTION.

CREATE VIEW CUSTOMERS_VIEW AS

SELECT name, age

FROM CUSTOMERS

WHERE age IS NOT NULL

WITH CHECK OPTION;

The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's
AGE column, because the view is defined by data that does not have a NULL value in the AGE
column.
The With Read Only Option
Specify WITH READ ONLY to indicate that the table or view cannot be updated.

CREATE VIEW customer_ro (name, language, credit)

AS SELECT cust_last_name, nls_language, credit_limit

FROM customers

WITH READ ONLY;

Creating Complex View:

CREATE VIEW myview AS


SELECT city, AVG(salary) average_salary
FROM employee
GROUP BY city
HAVING AVG(salary) > 50000;

References:

 (DATABASE DESIGN – 2ND EDITION by Adrienne Watt - Chapter 13)


 Dale Stokdyk Assistant Vice President of Product Marketing – STEM
 W3school

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