You are on page 1of 27

ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Database Management System (DBMS)


DBMS contains information about a particular enterprise
o Collection of interrelated data
o Set of programs to access the data
o An environment that is both convenient and efficient to use
Database Applications:
o Banking: all transactions
o Airlines: reservations, schedules
o Universities: registration, grades
o Sales: customers, products, purchases
o Online retailers: order tracking, customized recommendations
o Manufacturing: production, inventory, orders, supply chain
o Human resources: employee records, salaries, tax deductions
Databases touch all aspects of our lives

Purpose of Database Systems


In the early days, database applications were built directly on top of file systems
Drawbacks of using file systems to store data:
o Data redundancy and inconsistency
Multiple file formats, duplication of information in different files
o Difficulty in accessing data
Need to write a new program to carry out each new task
o Data isolation multiple files and formats
o Integrity problems
Integrity constraints (e.g. account balance > 0) become buried in program code
rather than being stated explicitly
Hard to add new constraints or change existing ones
Drawbacks of using file systems (cont.)
o Atomicity of updates
Failures may leave database in an inconsistent state with partial updates carried out
Example: Transfer of funds from one account to another should either complete or
not happen at all
o Concurrent access by multiple users
Concurrent accessed needed for performance
Uncontrolled concurrent accesses can lead to inconsistencies
Example: Two people reading a balance and updating it at the same time
o Security problems
Hard to provide user access to some, but not all, data
Database systems offer solutions to all the above problems

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 1 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

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 customer = record
customer_id : string;
customer_name : string;
customer_street : string;
customer_city : string;
end;
View level: application programs hide details of data types. Views can also hide information (such as
an employees salary) for security purposes.

View of Data
Fig. An architecture for a database system

Instances and Schemas


Similar to types and variables in programming languages
Schema the logical structure of the database
o Example: The database consists of information about a set of customers and accounts and the
relationship between them)
o Analogous to type information of a variable in a program
o Physical schema: database design at the physical level
o Logical schema: database design at the logical level
Instance the actual content of the database at a particular point in time
o Analogous to the value of a variable
Physical Data Independence the ability to modify the physical schema without changing the logical
schema
o Applications depend on the logical schema
o In general, the interfaces between the various levels and components should be well defined
so that changes in some parts do not seriously influence others.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 2 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Data Models
A collection of tools for describing
o Data
o Data relationships
o Data semantics
o Data constraints
Relational model
Entity-Relationship data model (mainly for database design)
Object-based data models (Object-oriented and Object-relational)
Semistructured data model (XML)
Other older models:
o Network model
o Hierarchical model

Data Manipulation Language (DML)


Language for accessing and manipulating the data organized by the appropriate data model
o DML also known as query language
Two classes of languages
o Procedural user specifies what data is required and how to get those data
o Declarative (nonprocedural) user specifies what data is required without specifying how to
get those data
SQL is the most widely used query language

Data Definition Language (DDL)


Specification notation for defining the database schema
Example: create table account (
account_number char(10),
branch_name char(10),
balance integer)
DDL compiler generates a set of tables stored in a data dictionary
Data dictionary contains metadata (i.e., data about data)
o Database schema
o Data storage and definition language
Specifies the storage structure and access methods used
o Integrity constraints
Domain constraints
Referential integrity (e.g. branch_name must correspond to a valid branch in the
branch table)
o Authorization

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 3 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Relational Model
Example of tabular data in the relational model

A Sample Relational Database

SQL (Structured Query Language)


SQL: widely used non-procedural language
o Example: Find the name of the customer with customer-id 192-83-7465
select customer.customer_name
from customer
where customer.customer_id = 192-83-7465
o Example: Find the balances of all accounts held by the customer with customer-id 192-83-
7465
select account.balance
from depositor, account
where depositor.customer_id = 192-83-7465 and
depositor.account_number = account.account_number
Application programs generally access databases through one of
o Language extensions to allow embedded SQL
o Application program interface (e.g., ODBC/JDBC) which allow SQL queries to be sent to a
database
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 4 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Database Design
The process of designing the general structure of the database:
Logical Design Deciding on the database schema. Database design requires that we find a good
collection of relation schemas.
o Business decision What attributes should we record in the database?
o Computer Science decision What relation schemas should we have and how should the
attributes be distributed among the various relation schemas?
Physical Design Deciding on the physical layout of the database

The Entity-Relationship Model


Models an enterprise as a collection of entities and relationships
o Entity: a thing or object in the enterprise that is distinguishable from other objects
Described by a set of attributes
o Relationship: an association among several entities
Represented diagrammatically by an entity-relationship diagram:

Transaction Management
A transaction is a collection of operations that performs a single logical function in a database
application
Transaction-management component ensures that the database remains in a consistent (correct)
state despite system failures (e.g., power failures and operating system crashes) and transaction
failures.
Concurrency-control manager controls the interaction among the concurrent transactions, to ensure
the consistency of the database.

Database Administrator
Coordinates all the activities of the database system; the database administrator has a good
understanding of the enterprises information resources and needs.
Database administrator's duties include:
o Schema definition
o Storage structure and access method definition
o Schema and physical organization modification
o Granting user authority to access the database
o Specifying integrity constraints
o Acting as liaison with users
o Monitoring performance and responding to changes in requirements

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 5 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Relational Database Concept

Dr. E.F. Codd proposed the relational model for database systems in 1970.

It is the basis for the relational database management system (RDBMS).

The relational model consists of the following:

Collection of objects or relations

Set of operators to act on the relations

Data integrity for accuracy and consistency

Definition of a Relational Database

A relational database is a collection of relations or two-dimensional tables.

Relating Multiple Tables

Each row of data in a table is uniquely identified by a primary key (PK).

You can logically relate data from multiple tables using foreign keys (FK).

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 6 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Relational Database Properties

A relational database:

Can be accessed and modified by executing structured query language (SQL) statements

Contains a collection of tables with no physical pointers

Uses a set of operators

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 7 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

SQL Statements

Basic SELECT Statement

SELECT *|{[DISTINCT] column|expression [alias],...}

FROM table;

SELECT *|{[DISTINCT] column|expression [alias],...}

FROM table;

SELECT identifies what columns

FROM identifies which table

Selecting All Columns

SELECT *

FROM departments;

Selecting Specific Columns

SELECT department_id, location_id

FROM departments;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 8 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Writing SQL Statements

SQL statements are not case sensitive.

SQL statements can be on one or more lines.

Keywords cannot be abbreviated or split across lines.

Clauses are usually placed on separate lines.

Indents are used to enhance readability.

Column Heading Defaults

Character and Date column headings are left justified

Number column headings are right-justified

Default heading display: Uppercase

Arithmetic Expressions

Create expressions with number and date data by using arithmetic operators.

Using Arithmetic Operators

SELECT last_name, salary, salary + 300

FROM employees;

Operator Precedence

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 9 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Multiplication and division take priority over addition and subtraction.

Operators of the same priority are evaluated from left to right.

Parentheses are used to force prioritized evaluation and to clarify statements.

Operator Precedence

SELECT last_name, salary, 12*salary+100

FROM employees;

Using Parentheses

SELECT last_name, salary, 12*(salary+100)

FROM employees;

Defining a Null Value

A null is a value that is unavailable, unassigned, unknown, or inapplicable.

A null is not the same as zero or a blank space.

SELECT last_name, job_id, salary, commission_pct

FROM employees;

Null Values in Arithmetic Expressions

Arithmetic expressions containing a null value evaluate to null.

SELECT last_name, 12*salary*commission_pct

FROM employees;

Defining a Column Alias

A column alias:

Renames a column heading

Is useful with calculations

Immediately follows the column name - there can also be the optional AS keyword between the column
name and alias

Requires double quotation marks if it contains spaces or special characters or is case sensitive

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 10 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Using Column Aliases

SELECT last_name "Name", salary*12 "Annual Salary"

FROM employees;

SELECT last_name AS name, commission_pct comm

FROM employees;

Concatenation Operator

A concatenation operator:

Concatenates columns or character strings to other columns

Is represented by two vertical bars (||)

Creates a resultant column that is a character expression

Using the Concatenation Operator

SELECT last_name||job_id AS "Employees"

FROM employees;

Literal Character Strings

A literal is a character, a number, or a date included in the SELECT list.

Date and character literal values must be enclosed within single quotation marks.

Each character string is output once for each row returned.

Using Literal Character Strings

SELECT last_name ||' is a '||job_id AS "Employee Details"

FROM employees;

Duplicate Rows

The default display of queries is all rows, including duplicate rows.

SELECT department_id

FROM employees;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 11 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Eliminating Duplicate Rows

Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.

SELECT DISTINCT department_id

FROM employees;

Displaying Table Structure

Use the iSQL*Plus DESCRIBE command to display the structure of a table.

DESC[RIBE] tablename;

Displaying Table Structure

DESCRIBE employees;

DESC employees;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 12 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Limiting the Rows Selected

Restrict the rows returned by using the WHERE clause.

SELECT *|{[DISTINCT] column|expression [alias],...}

FROM table

[WHERE condition(s)];

The WHERE clause follows the FROM clause.

Using the WHERE Clause

SELECT employee_id, last_name, job_id, department_id

FROM employees

WHERE department_id = 90 ;

Character Strings and Dates

Character strings and date values are enclosed in single quotation marks.

Character values are case sensitive, and date values are format sensitive.

The default date format is DD-MON-RR.

SELECT last_name, job_id, department_id

FROM employees

WHERE last_name = 'Whalen';

Comparison Conditions

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 13 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Using Comparison Conditions

SELECT last_name, salary

FROM employees

WHERE salary <= 3000;

Using the BETWEEN Condition

Use the BETWEEN condition to display rows based on a range of values.

SELECT last_name, salary

FROM employees

WHERE salary BETWEEN 2500 AND 3500;

Using the IN Condition

Use the IN membership condition to test for values in a list.

SELECT employee_id, last_name, salary, manager_id

FROM employees

WHERE manager_id IN (100, 101, 201);

Using the LIKE Condition

Use the LIKE condition to perform wildcard searches of valid search string values.

Search conditions can contain either literal characters or numbers:

% denotes zero or many characters.

_ denotes one character.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 14 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

SELECT first_name

FROM employees

WHERE first_name LIKE 'S%';

Using the LIKE Condition

You can combine pattern-matching characters.

SELECT last_name

FROM employees

WHERE last_name LIKE '_o%';

You can use the ESCAPE identifier to search for the actual % and _ symbols.

Using the NULL Conditions

Test for nulls with the IS NULL operator.

SELECT last_name, manager_id

FROM employees

WHERE manager_id IS NULL;

Logical Conditions

Using the AND Operator

AND requires both conditions to be true.

SELECT employee_id, last_name, job_id, salary

FROM employees

WHERE salary >=10000 AND job_id LIKE '%MAN%';

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 15 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Using the OR Operator

OR requires either condition to be true. OR requires either condition to be true.

SELECT employee_id, last_name, job_id, salary

FROM employees

WHERE salary >= 10000

OR job_id LIKE '%MAN%';

Using the NOT Operator

SELECT last_name, job_id

FROM employees

WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');

Rules of Precedence

SELECT last_name, job_id, salary

FROM employees

WHERE job_id = 'SA_REP'

OR job_id = 'AD_PRES'

AND salary > 15000;

Use parentheses to force priority.

SELECT last_name, job_id, salary

FROM employees

WHERE (job_id = 'SA_REP' OR job_id = 'AD_PRES')

AND salary > 15000;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 16 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

ORDER BY Clause

Sort rows with the ORDER BY clause

ASC: ascending order, default

DESC: descending order

The ORDER BY clause comes last in the SELECT statement.

SELECT last_name, job_id, department_id, hire_date

FROM employees

ORDER BY hire_date ;

Sorting in Descending Order

SELECT last_name, job_id, department_id, hire_date

FROM employees

ORDER BY hire_date DESC ;

Sorting by Column Alias

SELECT employee_id, last_name, salary*12 annsal

FROM employees

ORDER BY annsal;

Sorting by Multiple Column

The order of ORDER BY list is the order of sort.

SELECT last_name, department_id, salary

FROM employees

ORDER BY department_id, salary DES

You can sort by a column that is not in the SELECT list.

SELECT last_name, department_id, salary

FROM employees

ORDER BY department_id, salary DESC;


A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 17 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Manipulating Data

Data Manipulation Language

A DML statement is executed when you:

Add new rows to a table

Modify existing rows in a table

Remove existing rows from a table

A transaction consists of a collection of DML statements that form a logical unit of work.

The INSERT Statement Syntax

Add new rows to a table by using the INSERT statement.

INSERT INTO table [(column [, column...])]

VALUES (value [, value...]);

Only one row is inserted at a time with this syntax.

Inserting New Rows

Insert a new row containing values for each column.

List values in the default order of the columns in the table.

Optionally, list the columns in the INSERT clause.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 18 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

INSERT INTO departments

(department_id, department_name, manager_id, location_id)

VALUES (70, 'Public Relations', 100, 1700);

Enclose character and date values within single quotation marks.

Inserting Rows with Null Values

Implicit method: Omit the column from the column list.

INSERT INTO departments

(department_id, department_name )

VALUES (30, 'Purchasing');

Explicit method: Specify the NULL keyword in the VALUES clause.

INSERT INTO departments

VALUES (100, 'Finance', NULL, NULL);

The UPDATE Statement Syntax

Modify existing rows with the UPDATE statement.

UPDATE table

SET column = value [, column = value, ...]

[WHERE condition];

Update more than one row at a time, if required.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 19 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Updating Rows in a Table

Specific row or rows are modified if you specify the WHERE clause.

UPDATE employees

SET department_id = 70

WHERE employee_id = 113;

All rows in the table are modified if you omit the WHERE clause.

UPDATE copy_emp

SET department_id = 110;

The DELETE Statement

You can remove existing rows from a table by using the DELETE statement.

DELETE [FROM] table

[WHERE condition];

Deleting Rows from a Table

Specific rows are deleted if you specify the WHERE clause.

DELETE FROM departments

WHERE department_name = 'Finance';

All rows in the table are deleted if you omit the WHERE clause.

DELETE FROM copy_emp;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 20 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Database Transactions

A database transaction consists of one of the following:

DML statements which constitute one consistent change to the data

One DDL statement

One DCL statement

Database Transactions

Begin when the first DML SQL statement is executed

End with one of the following events:

A COMMIT or ROLLBACK statement is issued

A DDL or DCL statement executes (automatic commit)

The user exits iSQL*Plus

The system crashes

Advantages of COMMIT and ROLLBACK Statements

With COMMIT and ROLLBACK statements, you can:

Ensure data consistency

Preview data changes before making changes permanent

Group logically related operations

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 21 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Rolling Back Changes to a Marker

Create a marker in a current transaction by using the SAVEPOINT statement.

Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.

UPDATE...

SAVEPOINT update_done;

Savepoint created.

INSERT...

ROLLBACK TO update_done;

Rollback complete.

Implicit Transaction Processing

An automatic commit occurs under the following circumstances:

DDL statement is issued

DCL statement is issued

Normal exit from iSQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements

An automatic rollback occurs under an abnormal termination of iSQL*Plus or a system failure.

State of the Data before COMMIT or ROLLBACK

The previous state of the data can be recovered.

The current user can review the results of the DML operations by using the SELECT statement.

Other users cannot view the results of the DML statements by the current user.

The affected rows are locked; other users cannot change the data within the affected rows.

State of the Data after COMMIT

Data changes are made permanent in the database.

The previous state of the data is permanently lost.

All users can view the results.

Locks on the affected rows are released; those rows are available for other users to manipulate.

All savepoints are erased.


A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 22 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Committing Data

Make the changes.

DELETE FROM employees

WHERE employee_id = 99999;

1 row deleted.

INSERT INTO departments

VALUES (290, 'Corporate Tax', NULL, 1700);

1 row inserted.

Commit the changes.

COMMIT;

Commit complete.

State of the Data after ROLLBACK

Discard all pending changes by using the ROLLBACK statement:

Data changes are undone.

Previous state of the data is restored.

Locks on the affected rows are released.

DELETE FROM copy_emp;

22 rows deleted.

ROLLBACK;

Rollback complete.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 23 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Statement-Level Rollback

If a single DML statement fails during execution, only that statement is rolled back.

The Oracle server implements an implicit save point.

All other changes are retained.

The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement.

Read Consistency

Read consistency guarantees a consistent view of the data at all times.

Changes made by one user do not conflict with changes made by another user.

Read consistency ensures that on the same data:

Readers do not wait for writers.

Writers do not wait for readers.

Creating and Managing Tables

Naming Rules

Table names and column names:

Must begin with a letter

Must be 130 characters long

Must contain only AZ, az, 09, _, $, and #

Must not duplicate the name of another object owned by the same user

Must not be an Oracle server reserved word

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 24 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

The CREATE TABLE Statement

You must have:

CREATE TABLE privilege

A storage area

CREATE TABLE [schema.]table

(column datatype [DEFAULT expr][, ...]);

You specify: Table name

Column name, column data type, and column size

Referencing another Users Tables

Tables belonging to other users are not in the users schema.

You should use the owners name as a prefix to those tables.

Creating Tables

Create the table.

CREATE TABLE dept

(deptno NUMBER(2),

dname VARCHAR2(14),

loc VARCHAR2(13));

Table created.

Confirm table creation.

DESCRIBE dept;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 25 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Tables in the Oracle Database

User Tables:

Are a collection of tables created and maintained by the user

Contain user information

Data Dictionary:

Is a collection of tables created and maintained by the Oracle Server

Contain database information

Querying the Data Dictionary

See the names of tables owned by the user.

SELECT table_name

FROM user_tables ;

View distinct object types owned by the user.

SELECT DISTINCT object_type

FROM user_objects ;

View tables, views, synonyms, and sequences owned by the user.

SELECT *

FROM user_catalog ;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 26 of 27
ACT-506: Advanced Application of Computer in Textiles Lecture on Database

Dropping a Table

All data and structure in the table is deleted.

Any pending transactions are committed.

All indexes are dropped.

You cannot roll back the DROP TABLE statement.

DROP TABLE dept80;

Table dropped.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 27 of 27

You might also like