50
IT 21003 IT 21003 Database Administration Database Administration

IT 21003 Database Administration. This course is a study of the duties and responsibilities of a database administrator. This course covers setting up,

Embed Size (px)

Citation preview

IT 21003 IT 21003 Database AdministrationDatabase Administration

This course is a study of the duties and This course is a study of the duties and responsibilities of a database responsibilities of a database

administrator. administrator.

This course covers setting up, This course covers setting up, maintaining, and troubleshooting a maintaining, and troubleshooting a

distributed multi-user database. We will distributed multi-user database. We will utilize Oracle9i for our relational database.utilize Oracle9i for our relational database.

COURSECOURSE OBJECTIVE/LEARNING OUTCOMESOBJECTIVE/LEARNING OUTCOMES::

Understand the basic concepts of an Understand the basic concepts of an

ORACLE Database AdministratorORACLE Database Administrator  

COURSE TOPIC OUTLINE/PURPOSECOURSE TOPIC OUTLINE/PURPOSE::

To develop the next step in building computer To develop the next step in building computer competencies for a career in ORACLE Database competencies for a career in ORACLE Database

field.field.

Database HumorDatabase Humor

Database HumorDatabase Humor

IT HumorIT Humor

IT HumorIT Humor

Student HumorStudent Humor

Student HumorStudent Humor

One day a college professor was greeting his new college class. He stood up in front of the class and asked if anyone in the class was a

moron, and if they were, they should stand. After a minute a young man stood up. The professor then asked

thekid if he actually thought he was a moron. The kid replied, 'No, I just

didn't want to see you standing there all by yourself'

Software HumorSoftware Humor

Database ConceptsDatabase ConceptsReviewReview

Database Management Database Management Systems (DBMS)Systems (DBMS)

• Software that is designed to simplify Software that is designed to simplify and improve data managementand improve data management

• SupportsSupports– Methods of database accessMethods of database access– Manages user transactionsManages user transactions

• Establishes data securityEstablishes data security• Enforces integrityEnforces integrity• Optimizes performanceOptimizes performance• Controls concurrent data accessControls concurrent data access

Relational Database Relational Database Management Systems (RDBMS)Management Systems (RDBMS)

• A DBMS that supports data organization A DBMS that supports data organization based on the relational modelbased on the relational model

• Structure of the database is tabularStructure of the database is tabular– Tables are related to one another through Tables are related to one another through

common columnscommon columns– For example, For example, subject_areasubject_area and and coursecourse are are

two tables that are related by two tables that are related by subject_idsubject_id

• Oracle developed the first commercial Oracle developed the first commercial RDBMS in 1979RDBMS in 1979

Structured Query Structured Query Language (SQL)Language (SQL)

• SQL is the standard language for SQL is the standard language for relational databasesrelational databases– Users issue SQL commands to access and Users issue SQL commands to access and

manage data in a databasemanage data in a database– SQL is essentially a nonprocedural languageSQL is essentially a nonprocedural language

• SQL functionality has evolved SQL functionality has evolved significantly over the yearssignificantly over the years– 1979: First Oracle release1979: First Oracle release

• First commercial RDBMSFirst commercial RDBMS

Logical Data ModelLogical Data Model

• Provides a level of abstraction from physical Provides a level of abstraction from physical database design by representing data in database design by representing data in terms of “logical” or business entities and terms of “logical” or business entities and the relationships between themthe relationships between them

• Represents business information and rulesRepresents business information and rules• Provides input to physical database designProvides input to physical database design• Composed of three critical elementsComposed of three critical elements

– EntitiesEntities– AttributesAttributes– RelationshipsRelationships

EntityEntity

• An object of importanceAn object of importance• The object may be a tangible item The object may be a tangible item

such as a student or an abstract such as a student or an abstract concept such as attendanceconcept such as attendance

• Represented as a soft boxRepresented as a soft box• Example:Example:

Student

Company

represents

Sends for training

AttributeAttribute

• A fact that is a nondecomposable A fact that is a nondecomposable unit of information about an entityunit of information about an entity– Qualify, identify, classify, quantify, or Qualify, identify, classify, quantify, or

express the state of an entityexpress the state of an entity

• Example:Example:– Student id, last name, and first name Student id, last name, and first name

are attributes of the student entityare attributes of the student entity

ORACLE 9iORACLE 9i• What is ORACLE?What is ORACLE?

• ORACLE is a Relational Database ORACLE is a Relational Database Management System (DBMS)Management System (DBMS)

• Market share is 65-75%Market share is 65-75%• 3 out of 4 Fortune 100 companies 3 out of 4 Fortune 100 companies

run their enterprise applications on run their enterprise applications on OracleOracle

• Number one DBMS in the worldNumber one DBMS in the world

ORACLE DBAORACLE DBA• ORACLE Database AdministratorORACLE Database Administrator• Duties:Duties:

• Database CreationDatabase Creation• Database MaintenanceDatabase Maintenance• Backup/RepairBackup/Repair• Installing New ReleasesInstalling New Releases• Assessment of Database NeedsAssessment of Database Needs• Reports to CTO, ITOReports to CTO, ITO

ORACLE DBA JOBSORACLE DBA JOBS

• Over 5000 job openings currently Over 5000 job openings currently listed at online job search engineslisted at online job search engines

• Highest demand in IT is for OracleHighest demand in IT is for Oracle

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• NUMBER Data TypeNUMBER Data Type

– Used to store fixed or floating-point numbersUsed to store fixed or floating-point numbers– Syntax:Syntax:

• NUMBER [(Precision, Scale)]NUMBER [(Precision, Scale)]– Guaranteed to default to 38 digitsGuaranteed to default to 38 digits

• PrecisionPrecision– Total number of significant digitsTotal number of significant digits– Optional, defaults to the maximum supported by the Optional, defaults to the maximum supported by the

operating systemoperating system• ScaleScale

– Number of digits to the right of the decimal pointNumber of digits to the right of the decimal point– Can range from –84 to 127Can range from –84 to 127– Optional, defaults to zeroOptional, defaults to zero

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• NUMBER Data Type ExamplesNUMBER Data Type Examples

– NUMBERNUMBER• Maximum digits allowed by the system before or after Maximum digits allowed by the system before or after

the decimal pointthe decimal point

– Number (2)Number (2)• Two digits before the decimal lace and zero digits Two digits before the decimal lace and zero digits

afterafter– 9999

– Number (3,2)Number (3,2)• One digit before the decimal place and two digits afterOne digit before the decimal place and two digits after

– 9.999.99

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• CHAR Data TypesCHAR Data Types

– CHAR is used to store fixed-length character dataCHAR is used to store fixed-length character data• Syntax:Syntax:

– CHAR [(length)]CHAR [(length)]» Rarely used, for small codesRarely used, for small codes» y/n is good use of this typey/n is good use of this type

• LengthLength– Maximum 2,000 bytesMaximum 2,000 bytes– Optional, defaults to 1Optional, defaults to 1– Values are padded with blanks to the maximum lengthValues are padded with blanks to the maximum length

• Example:Example:– CHAR stores one characterCHAR stores one character– CHAR (10) stores 10 characters for a value of any lengthCHAR (10) stores 10 characters for a value of any length– Storing “Mike” in this data type would result in MIKE and six Storing “Mike” in this data type would result in MIKE and six

blanksblanks

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• VARCHAR2 Data TypeVARCHAR2 Data Type

– Used to Store variable-length character dataUsed to Store variable-length character data• Syntax:Syntax:

– VARCHAR2 (length)VARCHAR2 (length)• LengthLength

– Maximum 4,000 bytesMaximum 4,000 bytes– Mandatory that a length is specifiedMandatory that a length is specified– Values are not padded; exactly the length of the string Values are not padded; exactly the length of the string

is storedis stored• Example:Example:

– VARCHAR2 (10) stores up to 10 characters based on the VARCHAR2 (10) stores up to 10 characters based on the actual stringactual string

– Storing “MIKE” in this data type would not store extra Storing “MIKE” in this data type would not store extra characters or blankscharacters or blanks

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• DATE Data TypeDATE Data Type

– Used to store date and time to the precision of Used to store date and time to the precision of secondsseconds• Syntax:Syntax:

– DATEDATE• Stores date values from Jan. 1, 4712 BC, to Dec. 31, Stores date values from Jan. 1, 4712 BC, to Dec. 31,

4712 AD4712 AD• Stored internally as a number using seven bytes Stored internally as a number using seven bytes

default format maskdefault format mask– Retrieved and updated based on aRetrieved and updated based on a

» Default format mask is DD-MON-YYDefault format mask is DD-MON-YY» Changed by setting NLS_DATE_FORMAT parameterChanged by setting NLS_DATE_FORMAT parameter» TIME default is HH:MN:SETIME default is HH:MN:SE

Data Types, Data Types, Pseudocolumns, and Pseudocolumns, and

FunctionsFunctions• LOB Data TypeLOB Data Type

– There are three LOB or Large OBject Data There are three LOB or Large OBject Data TypesTypes• CLOB is used to store long variable-length character CLOB is used to store long variable-length character

stringsstrings• BLOB is used to store binary large objects, such as BLOB is used to store binary large objects, such as

bitmaps or audio or video imagesbitmaps or audio or video images• BFILE is a database reference to an operating BFILE is a database reference to an operating

system file that is stored outside of Oraclesystem file that is stored outside of Oracle

– LOB data types can contain up to 4 GB of dataLOB data types can contain up to 4 GB of data– Handling LOBS is a complex subjectHandling LOBS is a complex subject

SubQueriesSubQueries

• Increase the functionality of SELECT Increase the functionality of SELECT statements by allowing interrogation of statements by allowing interrogation of tables that are not used in the main tables that are not used in the main SELECT statementSELECT statement– A SELECT statement that occurs inside A SELECT statement that occurs inside

a condition of another SELECT a condition of another SELECT statementstatement• Each row of the parent statement is Each row of the parent statement is

compared with the result of the subquerycompared with the result of the subquery– If the comparison fails, the row is rejectedIf the comparison fails, the row is rejected

SubQueriesSubQueries

• Subquery Syntax and Rules:Subquery Syntax and Rules:– Same as the regular SELECT statement Same as the regular SELECT statement

without the ORDER BY clausewithout the ORDER BY clause– A subquery can have its own subqueriesA subquery can have its own subqueries– Normally used in the WHERE clause of the Normally used in the WHERE clause of the

parent SELECT statementparent SELECT statement– Common comparison operators for a Common comparison operators for a

subquerysubquery– Relational operators (=, <>, >, >=, <, <=)Relational operators (=, <>, >, >=, <, <=)– IN and NOT ININ and NOT IN– EXISTS and NOT EXISTSEXISTS and NOT EXISTS

Inserting, Updating, and Inserting, Updating, and Deleting DataDeleting Data

• Adding Data– Data is added to a table using the INSERT

statement• The INSERT statement can operate in two modes

– Adding exactly one row» Using the VALUES clause of the INSERT

statement– Copying zero or more rows

» Using the subquery clause of the INSERT statement

Building DatabasesBuilding Databases

• SchemaSchema– Collection of logical structures Collection of logical structures

(objects)(objects)– Owned by a database user and has Owned by a database user and has

the same name as that userthe same name as that user– Schema objects are created and Schema objects are created and

manipulated with SQL statements.manipulated with SQL statements.

Building DatabasesBuilding Databases

• Object OwnershipObject Ownership– Objects created by the user belong to Objects created by the user belong to

that user’s schemathat user’s schema• They have full controlThey have full control

– Other users can access these objects Other users can access these objects only if the owner grants accessonly if the owner grants access

– Even if access is granted, other users Even if access is granted, other users must prefix objects with owner’s must prefix objects with owner’s name unless public synonyms are name unless public synonyms are createdcreated

Building DatabasesBuilding Databases

• Building TablesBuilding Tables– Use the CREATE TABLE commandUse the CREATE TABLE command– Simplified Syntax:Simplified Syntax:

• CREATE TABLE table_nameCREATE TABLE table_name(column_name datatype [default (column_name datatype [default default_value] [NOT NULL],... (column_name default_value] [NOT NULL],... (column_name datatype [default default_value] [NOT NULL] );datatype [default default_value] [NOT NULL] );

Creating ObjectsCreating Objects

• Object TypesObject Types– Oracle uses the power of an RDBMS and extends it Oracle uses the power of an RDBMS and extends it

to include objectsto include objects• A type in the database for use in other structuresA type in the database for use in other structures• Does not result in storage allocationDoes not result in storage allocation

– Syntax:Syntax:• CREATE [OR REPLACE] TYPE object_type_name AS OBJECT CREATE [OR REPLACE] TYPE object_type_name AS OBJECT

(attribute_name datatype, attribute_name datatype)(attribute_name datatype, attribute_name datatype)

– Attributes are defined the same way as columns in Attributes are defined the same way as columns in tablestables• Must be unique within an object typeMust be unique within an object type• Normally, alphanumeric strings with a maximum of 30 Normally, alphanumeric strings with a maximum of 30

characterscharacters

Enforcing IntegrityEnforcing Integrity

• Integrity ConstraintsIntegrity Constraints– Declarative method of enforcing business rules in Declarative method of enforcing business rules in

the databasethe database– Defined with the corresponding table using the Defined with the corresponding table using the

CREATE TABLE or ALTER TABLE commandCREATE TABLE or ALTER TABLE command– Validated when constraints are defined and on Validated when constraints are defined and on

each INSERT, UPDATE and DELETEeach INSERT, UPDATE and DELETE– Five Types:Five Types:

• NOT NULLNOT NULL• Primary KeyPrimary Key• Unique KeyUnique Key• Foreign KeyForeign Key• CheckCheck

Establishing SecurityEstablishing Security

• Database AuthenticationDatabase Authentication– Verification and management of database Verification and management of database

users and their passwordsusers and their passwords• Users and their passwords are stored in the data Users and their passwords are stored in the data

dictionarydictionary

– To prevent unauthorized access, the To prevent unauthorized access, the password is validated during a connectpassword is validated during a connect

– Once connected, a user’s ability to view, Once connected, a user’s ability to view, create, and modify data is controlled via create, and modify data is controlled via other security featuresother security features

Establishing SecurityEstablishing Security

• Changing User PasswordChanging User Password– Users should change their passwords Users should change their passwords

regularly to avoid unauthorized accessregularly to avoid unauthorized access• Note: DBAs can’t see passwordsNote: DBAs can’t see passwords

– Syntax:Syntax:• ALTER USER user_name IDENTIFIED BY password;ALTER USER user_name IDENTIFIED BY password;

– The password must conform to Oracle’s The password must conform to Oracle’s naming restrictionsnaming restrictions• Maximum of 30 charactersMaximum of 30 characters• Must start with a letterMust start with a letter• Can include special characters such as $, #, and _Can include special characters such as $, #, and _• Not case sensitiveNot case sensitive

Establishing SecurityEstablishing Security

UsersUsers

PrivilegesPrivileges

Granting Privileges without RolesGranting Privileges without Roles

Establishing SecurityEstablishing Security

UsersUsers

PrivilegesPrivileges

Granting Privileges with RolesGranting Privileges with Roles

RolesRoles

Improving PerformanceImproving Performance

• IndexIndex– A structure that is defined for a table to provide A structure that is defined for a table to provide

faster access to table datafaster access to table data– Analogous to a book indexAnalogous to a book index

• To find a particular row in a table, the database engine To find a particular row in a table, the database engine searches the index, which identifies the row with a searches the index, which identifies the row with a pointerpointer

– A book usually contains one index; a table can A book usually contains one index; a table can contain any number of independent indexescontain any number of independent indexes

– An indexed search is much faster than a table An indexed search is much faster than a table search because an index’s internal structure is search because an index’s internal structure is designed to improve performancedesigned to improve performance• Oracle maintains a balanced B-tree structure for indexesOracle maintains a balanced B-tree structure for indexes

Improving PerformanceImproving Performance• Guidelines for Index CreationGuidelines for Index Creation

– Create primary and unique key constraintsCreate primary and unique key constraints• Oracle will automatically generate all unique indexesOracle will automatically generate all unique indexes

– Review all the queries in the applicationReview all the queries in the application• If all queries use existing unique indexes, then do not create If all queries use existing unique indexes, then do not create

any other indexesany other indexes

– If all queries do not us the unique indexes, determine If all queries do not us the unique indexes, determine whether they reference multiple columnswhether they reference multiple columns• If so, create composite indexes that contain those columnsIf so, create composite indexes that contain those columns

– If there are still queries that do not use an index, If there are still queries that do not use an index, determine whether those columns return fewer than determine whether those columns return fewer than 15% of the rows in a table15% of the rows in a table• If so, create single-column indexesIf so, create single-column indexes

– Do Not Add Indexes on Small TablesDo Not Add Indexes on Small Tables

Oracle DBAOracle DBA• The Role of the DBAThe Role of the DBA

– ResponsibilitiesResponsibilities::• Install and Upgrade Oracle ProductsInstall and Upgrade Oracle Products• Create Oracle DatabasesCreate Oracle Databases• Allocate and Plan Disk StorageAllocate and Plan Disk Storage• Set-Up UsersSet-Up Users• Modify Database StructuresModify Database Structures• Develop Backup and Recovery StrategiesDevelop Backup and Recovery Strategies• Maintain SecurityMaintain Security• Monitor and Optimize PerformanceMonitor and Optimize Performance• Select Software and Handle Licensing IssuesSelect Software and Handle Licensing Issues• Act as the Principle Oracle Support ContactAct as the Principle Oracle Support Contact

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle’s Memory and Process Oracle’s Memory and Process ArchitectureArchitecture

Database Buffer Cache Redo Log Buffer Shared Pool

Oracle Instance

System

GlobalArea

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle’s Memory and Process Oracle’s Memory and Process ArchitectureArchitecture

Background Background ProcessesProcesses

DedicatedDedicatedServerServerProcessProcess

DatabaseDatabaseWriterWriter

SystemSystemMonitorMonitor

ProcessProcessMonitorMonitor RecovererRecoverer LogLog

WriterWriter ArchiverArchiver CKPTCKPT

UserUserProcessProcess Run on Client MachinesRun on Client Machines

Shadow ProcessesShadow Processes

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Background Processes: SummaryBackground Processes: SummarySystem Monitor (SMON)System Monitor (SMON) Performs systemwide, housekeeping Performs systemwide, housekeeping

tasks such as database recoverytasks such as database recovery

Process Monitor (PMON)Process Monitor (PMON) Checks for failed processes and Checks for failed processes and backs them out in an orderly fashionbacks them out in an orderly fashion

Database Writer (DBWR)Database Writer (DBWR) Writes out data from the buffer Writes out data from the buffer cache in the SGA to the databasecache in the SGA to the database

Log Writer (LGWR)Log Writer (LGWR) Writes out contents of the log buffer Writes out contents of the log buffer to the redo log filesto the redo log files

Archiver (ARCH)Archiver (ARCH) Archives redo log files to Archives redo log files to offline/online storageoffline/online storage

Checkpoint Process (CKPT)Checkpoint Process (CKPT) Manages checkpoints – updates Manages checkpoints – updates database file headersdatabase file headers

Recoverer (RECO)Recoverer (RECO) Recovers distributed transactionsRecovers distributed transactions

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle’s Memory and Process ArchitectureOracle’s Memory and Process Architecture

DatabaseDatabase

Data SegmentData Segment

RollbackRollback SegmentSegment

Redo Log Redo Log File 1File 1

Redo Log Redo Log File 2File 2

OfflineOfflineStorageStorage

FilesFiles

Control Control File(s)File(s)

DATABASEDATABASE

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle Database – The Big PictureOracle Database – The Big Picture– ORACLE ARCHITECTUREORACLE ARCHITECTURE

““INSTANCE”INSTANCE”also known asalso known asORACLE_SIDORACLE_SID

Composed of Composed of Memory StructuresMemory Structures

System Global AreaSystem Global AreaBackground ProcessesBackground Processes

““DATABASE”DATABASE”also known asalso known as

DB_NAMEDB_NAME

Composed of Composed of Physical Disk FilesPhysical Disk Files

Data FilesData FilesRedo Log FilesRedo Log FilesControl FilesControl Files

OtherOtherMemoryMemory

StructuresStructures

OtherOtherStorageStorage

StructuresStructures

ORACLE_SID = DB_NAMEORACLE_SID = DB_NAME

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle Instances vs. Oracle DatabasesOracle Instances vs. Oracle Databases– Oracle InstanceOracle Instance

• Memory structure used for database managementMemory structure used for database management• Independent of the database – in memoryIndependent of the database – in memory• Consists of the System Global Area (SGA) and the Oracle Background ProcessesConsists of the System Global Area (SGA) and the Oracle Background Processes• Can mount (attach to) only one database at a timeCan mount (attach to) only one database at a time• Uniquely defined as ORACLE_SID or ORA_SID (OpenVMS only)Uniquely defined as ORACLE_SID or ORA_SID (OpenVMS only)

– Oracle DatabaseOracle Database• One or more Data FilesOne or more Data Files• Two or more Online Redo Log FilesTwo or more Online Redo Log Files• One or more Control FilesOne or more Control Files

– Should have at least two Control Files on separate disksShould have at least two Control Files on separate disks• Provides the actual physical storage of the database dataProvides the actual physical storage of the database data

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Oracle Instances vs. Oracle Databases cont’dOracle Instances vs. Oracle Databases cont’d• A Database is mounted by one or more InstancesA Database is mounted by one or more Instances• Data is accessible only when the database is openData is accessible only when the database is open• Uniquely defined as DB_NAME in init.ora (startup parameter file)Uniquely defined as DB_NAME in init.ora (startup parameter file)

Oracle Instances Oracle Instances and Database Conceptsand Database Concepts

• Instance-Database RelationshipInstance-Database Relationship

Instance Instance e.g. SID=ORA1e.g. SID=ORA1

Exclusive Database Exclusive Database e.g. DB_NAME = ORA1e.g. DB_NAME = ORA1

Exclusive DatabaseExclusive Database Parallel Server Architecture,Parallel Server Architecture, multiple Instances (Clustered Database)multiple Instances (Clustered Database)

Instance 1Instance 1e.g. SID = ORA1e.g. SID = ORA1

Instance 2Instance 2e.g. SID = ORA2e.g. SID = ORA2

Shared DatabaseShared Databasee.g. DB_NAME = ORA1e.g. DB_NAME = ORA1

END REVIEWEND REVIEW