Anda di halaman 1dari 28

Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Database Management System (DBMS)


A database management system is the software system that allows users to define, create and maintain a
database and provides controlled access to the data.
 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

Drawbacks of using file systems to store data


 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
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

Data Storage Hierarchy


In a DBMS, storage of data normally consists of the following six levels:
 Bit The smallest item of data is a single binary digit (a bit), either a 0 or 1.
 Character Multiple related bits are combined to form a character (or byte). For example, the letter
M, the number 8 and the special character $ are characters. A bit is the basic unit of primary and
secondary storage and a character is the basic unit of human perception.
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 1 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

 Field Multiple related characters are combined to form a field. For example, if we are processing
employees data of a company, we may have an employee-code field, an employee-name field, an
hours-worked field, an hourly-pay-rate filed and a tax-rate-deduction field etc.

 Record Multiple related fields are combined to form a record. For example, an employee record will
contain the fields containing the data of an employee, such as the employees code, name, hours-
worked, pay-rate, tax-rate deduction and so forth.
 File Multiple related records are combined to form a file. For example, a collection of all the
employee records of a company would be an employee file.
 Database Multiple related files are integrated to form a database. For example, an employee
database of an organization may integrate the records of multiple employee files, such as employee
salary files containing details of salary and taxation information of all employees, employee personnel
information file containing details of personnel information of all employees and employee skill-set
file containing details of various types of skills of all employees.

Benefits of the DBMS


The DBMS serves as the intermediary between the user and the database. The database structure itself is
stored as a collection of files, and the only way to access the data in those files is through the DBMS. The
DBMS receives all application requests and translates them into the complex operations required to fulfill

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 2 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

those requests. The DBMS hides much of the databases internal complexity from the application programs
and users.
The different advantages of DBMS are as follows.
 Improved data sharing - The DBMS helps create an environment in which end users have better
access to more and better-managed data. Such access makes it possible for end users to respond
quickly to changes in their environment.
 Improved data security - The more users access the data, the greater the risks of data security
breaches. Corporations invest considerable amounts of time, effort, and money to ensure that
corporate data are used properly. A DBMS provides a framework for better enforcement of data
privacy and security policies.
 Better data integration - Wider access to well-managed data promotes an integrated view of the
organizations operations and a clearer view of the big picture. It becomes much easier to see how
actions in one segment of the company affect other segments.
 Minimized data inconsistency - Data inconsistency exists when different versions of the same data
appear in different places. For example, data inconsistency exists when a companys sales department
stores a sales representatives name as Bill Brown and the companys personnel department stores
that same persons name as William G. Brown, or when the companys regional sales office shows
the price of a product as $45.95 and its national sales office shows the same products price as $43.95.
The probability of data inconsistency is greatly reduced in a properly designed database.
 Improved data access - The DBMS makes it possible to produce quick answers to ad hoc queries. From
a database perspective, a query is a specific request issued to the DBMS for data manipulationfor
example, to read or update the data. Simply put, a query is a question, and an ad hoc query is a spur-
of-the-moment question. The DBMS sends back an answer (called the query result set) to the
application. For example, end users, when dealing with large amounts of sales data, might want quick
answers to questions (ad hoc queries) such as:
What was the dollar volume of sales by product during the past six months?
What is the sales bonus figure for each of our salespeople during the past three months?
How many of our customers have credit balances of $3,000 or more?
 Improved decision making - Better-managed data and improved data access make it possible to
generate better-quality information, on which better decisions are based. The quality of the
information generated depends on the quality of the underlying data. Data quality is a comprehensive
approach to promoting the accuracy, validity, and timeliness of the data. While the DBMS does not
guarantee data quality, it provides a framework to facilitate data quality initiatives.
 Increased end-user productivity - The availability of data, combined with the tools that transform
data into usable information, empowers end users to make quick, informed decisions that can make
the difference between success and failure in the global economy.

Limitations of DBMS
Although the database system yields considerable advantages over previous data management approaches,
database systems do carry significant disadvantages. For example:
 Increased costs - Database systems require sophisticated hardware and software and highly skilled
personnel. The cost of maintaining the hardware, software, and personnel required to operate and
manage a database system can be substantial. Training, licensing, and regulation compliance costs are
often overlooked when database systems are implemented.
 Management complexity - Database systems interface with many different technologies and have a
significant impact on a companys resources and culture. The changes introduced by the adoption of a
database system must be properly managed to ensure that they help advance the companys
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 3 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

objectives. Given the fact that database systems hold crucial company data that are accessed from
multiple sources, security issues must be assessed constantly.
 Maintaining currency - To maximize the efficiency of the database system, you must keep your
system current. Therefore, you must perform frequent updates and apply the latest patches and
security measures to all components. Because database technology advances rapidly, personnel
training costs tend to be significant. Vendor dependence. Given the heavy investment in technology
and personnel training, companies might be reluctant to change database vendors. As a consequence,
vendors are less likely to offer pricing point advantages to existing customers, and those customers
might be limited in their choice of database system components.
 Frequent upgrade/replacement cycles - DBMS vendors frequently upgrade their products by adding
new functionality. Such new features often come bundled in new upgrade versions of the software.
Some of these versions require hardware upgrades. Not only do the upgrades themselves cost money,
but it also costs money to train database users and administrators to properly use and manage the
new features.

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.

Fig. Levels of abstraction of a database system

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 4 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management 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.

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

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

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:

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 5 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Manag
Apparel/Management Lecture # Database Management System

Relational Model
 Example of tabular data in the relational model

A Sample Relational Database

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 6 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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

Structured Query Language (SQL)


 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 7 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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

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).

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 8 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 9 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

SQL Statements

Creating and Managing Tables

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 10 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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

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

Creating Tables

CREATE TABLE dept


(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Table created.

Displaying Table Structure


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

DESC[RIBE] tablename;
DESCRIBE employees;
DESC employees;
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 11 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Confirm table creation.

DESCRIBE dept;

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 ;

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 12 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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;

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;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 13 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Operator Precedence

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

Using Column Aliases


SELECT last_name "Name", salary*12 "Annual Salary"
FROM employees;

SELECT last_name AS name, commission_pct comm


FROM employees;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 14 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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;

Eliminating Duplicate Rows


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

SELECT DISTINCT department_id


FROM employees;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 15 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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';

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 16 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Comparison Conditions

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);

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 17 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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.

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.

The ESCAPE Option


When you need to have an exact match for the actual % and _ characters, use the ESCAPE option. This option
specifies what the escape character is. If you want to search for strings that contain SA_, you can search for it
using the following SQL statement:

SELECT employee_id, last_name, job_id


FROM employees
WHERE job_id like %SA\_% ESCAPE \;

EMPLOYEE_ID LAST_NAME JOB_ID


149 Zlotkey SA_MAN
174 Abel SA_REP
176 Taylor SA_REP
178 Grant SA_REP

The ESCAPE option identifies the backslash (\) as the escape character. In the pattern, the escape character
precedes the underscore (_). This causes the Oracle Server to interpret the underscore literally.

Using the NULL Conditions


Test for nulls with the IS NULL operator.

SELECT last_name, manager_id


FROM employees
WHERE manager_id IS NULL;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 18 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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%';

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;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 19 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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;

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 DESC;

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


SELECT last_name, department_id, salary
FROM employees
ORDER BY employee_id, salary DESC;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 20 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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.

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.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 21 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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.

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;

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 22 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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 employees;

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
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 23 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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

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.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 24 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

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.

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.

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.

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 25 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Database Connectivity
Oracle provides Oracle Net Services which is a suite of components that provides a connectivity solution.
Oracle Net Service consist of
Oracle Net - software component that initiates, establishes and maintains connections between client
and servers, it contains two components
o oracle network foundation layer - responsible for establishing and maintaining connections
o oracle support protocol - responsible for mapping Transparent Network Substrate (TNS)
Oracle Net Listener - Listens for incoming requests from users
Oracle Connection Manager - GUI based utility
Oracle Net Configuration Assistant - GUI based utility , configure network components
Oracle Net Manager - GUI based utility, configures various naming methods and listeners
Oracle Enterprise Manager - can do everything

Database Service Name


Databases logically appear as services, you identify each database in your system by its service name. The
database instance name refers to the SGA and processes that make up the instance, this is commonly referred
as the Oracle System Identifier (SID), normally a database is only associated with one instance apart from
when using a RAC environment. You can uniquely identify each database by using a global database name
which is in the format of database_name.database_domain (sales.us.acme.com).

Connection
You need two pieces of information to connect to a database
Name of the database server - name of the service that oracle is supplying
Location of the address - need to supply the protocol type (default TCP) , hostname and the port
number (default 1521)

Oracle supports a number of protocols TCP, SDP, TCP with secure sockets and named pipes. There are two
ways to connect to oracle dedicated or Shared Server, both could be running at the same time on the same
server. There are 4 connection types
Dedicated - direct handoff (client and server are on the same computer)
Dedicated - redirect (client and server are on different computers)
Shared server - direct handoff (client and server are on the same computer)
Shared server - redirect (client and server are on different computers)

To connect to a oracle service you would use a connect string


connect scott/tiger@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=sales)(PORT=1521))
Connect
(CONNECT_DATA=(SERVICE_NAME=sales.us.acme.com)))
String
connect scott/tiger@sales

Listener
Oracle listener only runs on the server and listens for incoming client connections, a utility called lsnrctl is used
to manage the listener process. The listeners role is
The database registers information about the services, instances and service handlers with the listener
The client makes the initial connection with the listener
The listener receives and verifies the connection and forwards it to the service handler, once the
listener hands off the request, the listener is out of the picture.
A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 26 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

The listener.ora file contains the listener configuration details, with oracle 10g the listener can automatically register
itself with the database, The PMON process updates the listener.ora file with any new databases.

1. Register the default listener to the instance


Dynamically register # alter system set instance_name = P01;
the default listener # alter system set service_name = P01;
Note: port 1521 is assumed, you do not need to update the listener.ora file

1. Create the listener (use Net Manager)


2. Create the Net Service name (Use Net Configuration Assistant)
Dynamically register
3. Register the service with the instance
a non-default
# alter system set local_listener = 'P01_1522';
listener
# alter system register;
Note: you need to update the listener.ora and tnsnames.ora files

The listener utility lsnrctl can be used to manage the listener


starting lsnrctl start

stopping lsnrctl stop

status lsnrctl status

Reloading configuration lsnrctl reload

Display Services lsnrctl services

Save the configuration lsnrctl save_config

Set tracing ON lsnrctl trace

Help lsnrctl help

current_listener, displaymode, inbound_connection_timeout, log_status, log_file,


Number of set/show commands
log_directory, trc_level, trc_file, trc_directory, password (only set is available)

An example listener.ora file


# listener.ora Network Configuration File:
C:\oracle\product\10.2.0\db_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME = C:\oracle\product\10.2.0\db_1)
(PROGRAM = extproc)
)
listener.ora
)
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = laptop)(PORT = 1521))
)
)

A.N.M. Bazlur Rashid, Assistant Professor (Computer) & Head, Department of Allied Engineering, Bangladesh University of Textiles / Page 27 of 28
Application of Computer in Yarn/Fabric/Wet/Apparel/Management Lecture # Database Management System

Naming and Connectivity


Oracle also several types of naming services
local naming - uses a file called tnsnames.ora on the client
host naming - uses host file or DNS to resolve hostname, you must use TCP.
easy connect naming - can supply the service information on the command line
external naming - Use third party naming services to resolve service names i.e. NIS
directory naming - centralized LDAP-compliant directory server to resolve service names
c:\> set ORACLE_SID=P01
Host Naming c:\> sqlplus vallep/secret@laptop
Note: DNS will resolve the laptop name
c:\> sqlplus vallep/secret@laptop:1522/P01
Easy Connect
c:\> sqlplus vallep/secret@//laptop/P01
Add an entry in the tnsnames.ora file
P01 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = laptop)(PORT = 1521))
)
Local Naming (CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = P01)
)
)
Note:can use the TNS_ADMIN environment variable to point to different tnsnames.ora
files

The sqlnet.ora file specifies which order to try (bit like the nsswitch.conf file in unix)
NAMES.DIRECTORY_PATH=(TNSNAMES,EZCONNECT,HOSTNAME)
sqlnet.ora
NAMES.DEFAULT_DOMAIN=DATADISK.CO.UK
File locations
adaptors $oracle_home/bin/adapters
listener $oracle_home/network/admin/listener.ora
tnsnames $oracle_home/network/admin/tnsnames.ora
sqlnet $oracle_home/network/admin/sqlnet.ora
listener log $oracle_home/network/log.listener.log
server tracing $oracle_home/network/trace/listener.trc

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