monitoring space and users - metropolitan state...

84
Monitoring Space and Users

Upload: dinhthuan

Post on 10-Mar-2018

215 views

Category:

Documents


2 download

TRANSCRIPT

Monitoring Space and

Users

Space and User Topics

•Adding Tablespaces

•Creating Users

•Managing Segments

Tablespaces• Are basic storage units for the data of the database.

All segments (tables and indexes) must reside in a tablespace.

• Are basic storage units for the data dictionary’s segments. These segments are stored and maintained by Oracle in the SYSTEM tablespace.

• Hold the segments that contain the UNDO information necessary to rollback transactions.

• Must be associated with one or more O/S data files.

Segments, Extents and db Blocks• Segments are the general name given to database

objects that store data (e.g. Tables and Indexes). (objects that don’t store data (e.g. Views and Synonyms) have their definitions stored in the System tables.

• Segments are comprised of Extents. A Segment must have one or more Extents. When an extent is filled with data, the database automatically allocates a new extent.

• Each Extent is comprised of one or more db Blocks. The db Blocks in each Extent must be located contiguously on the disk.

Segment Storage

Segment

Extent 1(4 Blocks)

Extent 2(3 Blocks)

Extent 3(5 Blocks)

Extents may be located anywhere on the storage media. They may even be located on different files. The blocks within each extent must be located contiguously.

Extent Management

• Dictionary Managed Extents are maintained by the data dictionary. Extents may be of any number of db_blocks. The extents may be of different sizes (even for the same table). Dictionary managed extents were the default prior to Oracle version 9.

• Locally Managed Extents are maintained by a bitmap index placed on the file. The index indicates if each block is available or used. The extents are allocated when the tablespace is created. All extents must be the same size and this size may not be changed. Locally managed extents are the default – Dictionary managed extents cannot be used in Oracle version 9.2 and later.

Locally Managed Extents

• Eliminates the need for repeated data dictionary reads and writes.

• Does not require SMON to coalesce (defragment) the tablespace.

• Will usually waste less space if there are frequent reads and writes on the data.

• Requires less maintenance from the DBA.

Advantages of Locally Managed Extents over Dictionary Managed Extents.

Locally Managed Extents Map(Map of a hypothetical file)

11 1 2 2 2 3 3 3 13 1 1 121

22 2 1 1 1 2 2 2 212

3 3 3 3 3 3 43 4 4 43

44 4 5 5 5 45 4 4 44

Each cell represents the area of one db_block. The first extent of the EMP table has been allocated four blocks. All extents are exactly the same size and were allocated when the tablespace was created.

EMP Table

DEPT Table

CUST Table

Guidelines for Tablespaces

• generating REDO information for data recovery.• generate UNDO information supporting rollback

operations.• taken offline for maintenance and backup.• files may be moved to other disks for improved

database performance.• being placed in a read only mode by the DBA.

All tablespaces must follow certain guidelines regardless of how they are tracked by the database. These guidelines include:

Creating a Dictionary Tablespace(obsolete)

SQL> Create Tablespace Data2 Datafile3 '/oraclec/data/DB08/Disk1/data01.dbf'4 Size 2M Reuse5 Default Storage (6 Initial 32K Next 32K7 Minextents 2 Maxextents 1218 PctIncrease 0)9 Extent Management Dictionary;

Tablespace created.

Default Storage Parameters

Parameter Description

Initial The first extent created will be of this size. It should be defined as a multiple of the db_block_size. All segments must contain at least this one extent.

Next The second extent created will be of this size.

Minextents The number of extents created when the segment is first created. For example, if this value is set to 2, an extent of the size specified in Initial plus an extent of the size specified in Next is created when the segment is created.

Default Storage Parameters (cont.)Parameter Description

Maxextents The maximum number of extents that can be assigned to the segment. If all extents fill with data and this parameter is reached, a “cannot extend” error will be returned. If no value is specified, the default value of 121 will be enforced. If you try to provide a value greater than 121 for this parameter, it will default back to 121.

PctIncrease Percent Increase allows your segment to grow at an increasing rate. The first two extents will be of a size determined by the Initial and Next parameters. The third extent will be 1 + PCTINCREASE/100 times the second extent. The fourth extent will be 1 + PCTINCREASE/100 times the third extent, etc. PctIncrease can be set at any integer between 0 and 100. If not specified, the default value will be 50.

Tablespace with Two Data FilesSQL> Create Tablespace INDEXES

2 Datafile3 '/oraclec/data/DB08/Disk3/indexes01.dbf'4 Size 2M Reuse,5 '/oraclec/data/DB08/Disk4/indexes02.dbf'6 Size 2M Reuse7 Default Storage (8 Initial 32K Next 32K9 Minextents 2 Maxextents 121 PctIncrease 0)

10 Extent Management Dictionary;

Tablespace created

The DATAFILE keyword is used only once.

View of dba_tablespaces

SQL> select * from dba_tablespaces;

TABLES INITIAL NEXT MIN MAX PCT MIN NAME EXTENT EXTENT EXT EXT INCR EXL STATUS CONTENTS LOGGING------ ------- -------- --- --- ---- --- ------ --------- -------SYSTEM 10240 10240 1 121 50 0 ONLINE PERMANENT LOGGINGRBS 131072 131072 2 50 0 0 ONLINE PERMANENT LOGGINGTEMP 512000 512000 1 121 0 0 ONLINE PERMANENT LOGGINGTOOLS 10240 10240 1 121 50 0 ONLINE PERMANENT LOGGINGUSERS 10240 10240 1 121 50 0 ONLINE PERMANENT LOGGINGDATA 32768 32768 2 121 0 0 ONLINE PERMANENT LOGGINGINDEXES 32768 32768 2 121 0 0 ONLINE PERMANENT LOGGING

Columns in dba_tablespacesColumn Name DescriptionMIN_EXTLEN This is the minimum extent size that may be created by any

segment in the tablespace.

STATUS This can be AVAILABLE, ONLINE or OFFLINE. There will be several situations when a tablespace would be taken offline. Note that when the tablespace is created, it is immediately brought online and is available for use.

CONTENTS This can be PERMANENT or TEMPORARY. Use Temporary if the tablespace is to be used by Oracle for sorts. You can’t create objects in a temporary tablespace.

LOGGING LOGGING indicates that activity on the segments in this tablespace are recorded in the REDO log. NOLOGGINGindicates activity is not recorded.

Data Files and TablespacesSQL> select file_name, tablespace_name,2 bytes, blocks, status3 from dba_data_files4 order by tablespace_name;

TABLESPACEFILE_NAME _NAME BYTES BLOCKS STATUS-------------------------------------- ---------- --------- ------ ---------/oraclec/data/DB08/Disk1/data01.dbf DATA 2097152 256 AVAILABLE/oraclec/data/DB08/Disk3/indexes01.dbf INDEXES 2097152 256 AVAILABLE/oraclec/data/DB08/Disk4/indexes02.dbf INDEXES 2097152 256 AVAILABLE/oraclec/data/DB08/Disk1/indx01.dbf INDX 5242880 640 AVAILABLE/oraclec/data/DB08/Disk1/rbs01.dbf RBS 20971520 2560 AVAILABLE/oraclec/data/DB08/Disk1/system01.dbf SYSTEM 104857600 12800 AVAILABLE/oraclec/data/DB08/Disk1/temp01.dbf TEMP 10485760 1280 AVAILABLE/oraclec/data/DB08/Disk1/tools01.dbf TOOLS 8388608 1024 AVAILABLE/oraclec/data/DB08/Disk1/users01.dbf USERS 5242880 640 AVAILABLE

9 rows selected.

Locally Managed Tablespaces

SQL> Create Tablespace DATA22 Datafile3 '/oraclec/data/DB08/Disk1/data201.dbf'4 Size 4M Reuse5 Uniform Size 32K;

Local extent management is the default so it does not need to be specified. All extents will be 32K and the uniform extent size cannot be changed.

Adding a New Data File to an Existing Tablespace

The following statement will add a data file to the DATA tablespace. The data file may be saved on any available disk.

SQL> Alter Tablespace DATA2 Add Datafile3 '/oraclec/data/DB08/Disk1/data02.dbf'4 Size 4M Reuse;

Tablespace altered.

Creating Temporary Tablespaces

• The tablespace will be locally managed, contain no permanent objects, and no REDO information will be generated.

• The temporary tablespaces should not be backed up.

• The blocks in the tablespace will not be formatted upon creation (sparse file).

• Different groups of users can be assigned different temporary tablespaces.

SQL> Create Temporary Tablespace TEMP12 Tempfile3 '/oraclec/data/DB08/Disk1/temp101.dbf'4 Size 4M Reuse5 Uniform Size 64K;

Create the temporary tablespace as shown below.

Data Files and Temp Files• Data File

– Allocates space immediately when created. – Users and the DBMS are allowed to create objects and

store them in the file. – Objects stored in the file are permanent and will remain

until explicitly removed.• Temp File

– Only the header is immediately created. Space for the file is allocated as needed.

– Users may not create objects and store them in the file. – The contents of the file are removed when the database is

shut down. – The uniform extent size should be set to the size of the

sort_area_size parameter.

Relocating a Data File

• Take the tablespace offline so no one can access the data while the file is being moved.

• Use the operating system command to move the file from one location to another. If you are using unix, remember that file names are case sensitive. Also, don’t press enter in the middle of a file name or quoted string.

• Rename the data file in Oracle.

• Bring the tablespace back online so its data can be accessed.

Below are the steps you must follow to move a data file to a new location.

Commands to Move the File

SQL> Alter Tablespace DATA Offline;

Tablespace altered.

SQL> !mv '/oraclec/data/DB08/Disk1/data02.dbf''/oraclec/data/DB08/Disk2/data02.dbf'

SQL> Alter Tablespace DATA2 Rename Datafile '/oraclec/data/DB08/Disk1/data02.dbf'3 To '/oraclec/data/DB08/Disk2/data02.dbf';

Tablespace altered.

SQL> Alter Tablespace DATA Online;

Tablespace altered.

Bring the tbspace online.

Take the tbspace offline.

Rename the tbspace in SQL.

Use the O/S to move the file.

Defragmenting a Tablespace

• Oracle first scans the disk and tries to find an exact fit.

• Oracle next scans the disk looking for a best fit.

• If Oracle doesn’t have enough contiguous space to acquire the extent, SMON coalesces the free space if the PctIncrease value in the tablespace’s default storage clause exceeds zero. The contiguous space is acquired for the extent, if possible. If the space isn’t available, a Cannot Extent error is generated.

Segments need to acquire new extents as more data are added. Tablespaces with Dictionary Managed Extents acquire extents according to the following set of rules. These rules frequently leave the tablespace fragmented with segments of unused free space when there is significant activity on the segments.

Detecting FragmentationSQL> Select * From DBA_Free_Space Order By Tablespace_Name;

TABLESPACE_NAME FILE_ID BLOCK_ID BYTES BLOCKS RELATIVE_FNO---------------- ------- -------- ---------- ------ ------------DATA 7 46 1728512 211 7DATA 7 18 98304 12 7DATA 11 2 4186112 511 11DATA2 12 13 1998848 244 12DATA2 10 17 4063232 496 10INDEXES 8 6 2056192 251 8INDEXES 9 6 2056192 251 9INDX 6 2 5234688 639 6RBS 3 642 15720448 1919 3RBS 3 450 1048576 128 3SYSTEM 1 6979 47693824 5822 1SYSTEM 1 6971 65536 8 1TEMP 4 2 10477568 1279 4TOOLS 2 18 32768 4 2TOOLS 2 10 32768 4 2TOOLS 2 22 8216576 1003 2TOOLS 2 14 32768 4 2TOOLS 2 6 32768 4 2TOOLS 2 2 32768 4 2USERS 5 2 5234688 639 5

Number of FragmentsSQL> select tablespace_name,

2 sum(bytes) as bytesfree,3 count(*) as NSegments3 from dba_free_space4 group by tablespace_name;

TABLESPACE_NAME NSEGMENTS BYTESFREE----------------- --------- ----------DATA 3 6012928DATA2 2 6094848INDEXES 2 4177920INDX 1 5234688RBS 2 16769024TEMP 1 10477568TOOLS 6 8380416USERS 1 52346888 rows selected.

The results of the query show the number of segments of Free Space as the total bytes of Free Space in the tablespace. To reduce the number of segments of free space, enter the following for each tablespace.ALTER TABLESPACEtablespacenameCOALESCE;

Read-Only Tablespaces

SQL> Alter Tablespace DATA2 Read Only;

Tablespace altered.

SQL> connect jerry/welcomeConnected.

Place the tablespace in a READ ONLYmode. No modification of data in this tablespace will be allowed when the tablespace is in this mode.

Connect to Jerry’s account to test the Read Only mode.

Read-Only TablespacesSQL> Insert Into EMP Values

2 (10, 'Jack', 60000, 'MIS', Sysdate);Insert Into EMP Values

*ERROR at line 1:ORA-00372: file 7 cannot be modified at this timeORA-01110 data file 7: '/oraclec/data/DB08/Disk1/data01.dbf'

SQL> Update EMP Set Salary = 75000;Update EMP Set Salary = 75000;

*ERROR at line 1:ORA-00372: file 7 cannot be modified at this timeORA-01110 data file 7: '/oraclec/data/DB08/disk1/data01.dbf'

SQL> Alter Tablespace DATA Read Write;

Resizing an Existing Data File

SQL> Alter Database DB082 Datafile3 '/oraclec/data/DB08/Disk2/data02.dbf'4 Resize 8M;

Database altered.

The ALTER DATABASE statement below will resize the data file to the value show. The following rules apply to resizing a data file.•You can always increase the size of a data file (as long as there is available disk space).

•To decrease the size of the file, the file must be empty. You may need to temporarily move some objects before reducing the file size.

Removing Files and TablespacesSQL> Alter Database DB082 Datafile3 '/oraclec/data/DB08/Disk2/data202.dbf'4 Offline Drop;

Database altered.

SQL> Drop Tablespace Data3;Tablespace dropped.

SQL> Drop Tablespace DATA32 Including Contents;

Tablespace dropped.

SQL> Drop Tablespace DATA32 Including Contents3 Cascade Constraints;

Tablespace dropped.

Remove a file from a tablespace with the statement. S'hould be used with caution.

Remove a tablespace with the statement. The tablespace must be empty.

Remove a tablespace and all of its objects with the statement on the right.

If a table in the tablespace is referenced by another table, you must use the Cascade Constraints clause.

Managing Users

Create a New UserSQL> Create User Elaine password is2 Identified By Welcome case sensitive3 Default Tablespace DATA 4 Temporary Tablespace Temp5 Quota 5M on DATA6 Quota Unlimited On Temp;

User created.

SQL> connect Elaine/welcomeERROR:ORA-01045: user ELAINE lacks CREATE SESSION privilege; logon denied

Warning: You are no longer connected to ORACLE.

Granting the Connect and Resource Roles

SQL> Grant Connect, Resource To Elaine;

Grant succeeded.

SQL> Connect Elaine/WelcomeConnected.

SQL>

Password Expire

SQL> Create User George2 Identified By Welcome3 Default Tablespace DATA4 Quota 5M on DATA5 Password Expire;

User created.

SQL> Grant Connect,2 Resource To George;

Grant succeeded.

Creating the user with the Password Expire clause will force the new user to change his/her password the first time (s)he logs onto the database.

User Forced to Change Password

SQL> Connect George/WelcomeERROR:ORA-28001: the password has expired

Changing password for GeorgeNew password:Retype new password:Password changedConnected.

When George first connects to the database, he must enter (and confirm) a new password.

Entered data will not display

New User Script File

Create User &1Identified By welcomeDefault Tablespace DataQuota 5M on DataTemporary Tablespace TempQuota Unlimited on Temp;Grant Connect, Resource to &1;

The following text should be entered into a script file with the name of newuser.sql. The & represents a variable that will be passed from the command line when the script is executed.

Executing the newuser script

• Access an account with the DBA privilege and enter the following to create a user named JERRY.

SQL> @newuser jerry

The name JERRY will be substituted for &1everywhere in the script. Create new users with this script replacing JERRY with other user names.

User with DBA Privileges

• Create a user with the newuser script (granting the connect and resource roles.)

• Grant the DBA privilege to the user.

SQL> @newuser SupermanSQL> Grant DBA To Superman;

Viewing Data on Users

USERNAME USER PASSWORD ACCOUNT LOCK EXPIRY DEFAULT TEMPORARY CREATED PROFILEID STATUS DATE DATE TABLESPACE TABLESPACE

-------- ---- ----------------- ------- ---- ------ ---------- ---------- --------- -------DBSNMP 16 E066D214D5421CCC OPEN SYSTEM SYSTEM 02-JAN-15 DEFAULT ELAINE 30 092CA7BCF360A117 OPEN DATA TEMP 26-MAY-15 DEFAULTGEORGE 31 666D4EF49E031243 OPEN DATA TEMP 01-JUN-15 DEFAULT JERRY 27 88F7D29BBCA21A5E OPEN DATA TEMP 26-MAY-15 DEFAULTKRAMER 32 621FB93B53107919 OPEN DATA TEMP 01-JUN-15 DEFAULT OUTLN 11 4A3BA55E08595C81 OPEN SYSTEM SYSTEM 02-JAN-15 DEFAULT SUPERMAN 26 42153BFAF4C2A023 OPEN DATA TEMP 26-MAY-15 DEFAULT SYS 0 D4C5016086B2DC6A OPEN SYSTEM TEMP 02-JAN-15 DEFAULT SYSTEM 5 D4DF7931AB130E37 OPEN TOOLS TEMP 02-JAN-15 DEFAULT TRACESVR 19 F9DA8977092B7B81 OPEN SYSTEM SYSTEM 02-JAN-15 DEFAULT

SQL> select2 username, user_id, password, account_status,3 lock_date, expiry_date,4 default_tablespace, temporary_tablespace,5 created, profile6 from dba_users order by username;

Columns in dba_usersColumn Name DescriptionUSERNAME The name that was created for the user.

USER_ID Internal ID supplied by the database.

PASSWORD Encrypted password. Eighteen hexadecimal characters.

ACCOUNT_STATUS

The status may be OPEN , CLOSED , or LOCKED. The account may be closed (deleted) but the user’s objects can continue to exist. The account may be Locked (inaccessible) while the user is not available.

LOCK_DATE Date the account was locked.

Columns in dba_users (cont.)Column Name DescriptionEXPIRY_DATE The date when the user’s password is set to expire. The

password’s lifetime is set in the profile assigned to the user.

DEFAULT_TABLESPACE

The tablespace where the user’s Segments will be stored if not explicitly located when the Segment is created.

TEMPORARY_TABLESPACE

The temporary tablespace assigned to the user that the database will use to store data for large . ries or sorts. If not specified, the tablespace TEMP will be used.

CREATED The date the user’s account was created.

PROFILE The name of the profile assigned to the user. If no profile is explicitly assigned, the database will assign a profile named DEFAULT .

Modifying the USER ObjectSQL> Alter User Superman2 Identified By loislane;

User Altered.

SQL> Alter User Jerry2 Quota 10M On DATA23 Quota Unlimited On INDEXES;

User altered.

SQL> Alter User Elaine2 Quota 10M On DATA23 Quota Unlimited On INDEXES;

User altered.

The Superman’s password is changed to loislane.

JERRY and ELAINE are given different quotas on DATA2 and INDEXES.

Dropping Users

SQL> Drop User Kramer;User dropped.

SQL> Drop User Kramer Cascade;User dropped.

Drop the user KRAMER. Kramer’s account status will be closed but his objects will remain.

KRAMER and his objects are gone. His account will no longer exist.

Locking User’s Accounts

SQL> Alter User Kramer Account Lock;User altered.

SQL> Alter User Kramer Account UnLock;User altered.

Lock KRAMER’s account so it can’t be accessed. (Maybe he’s going on vacation.)

Unlock the account to make it accessible.

Viewing Logged In Users

The query below will display all the users who are currently logged into the database.

SQL> select2 SID, serial#, username3 from v$session where username is not null;

SID SERIAL# USERNAME---------- ---------- ------------------

8 54 SYSTEM 8 rows selected.

Use the following statement to terminate a user’s session.

SQL> Alter System Kill Session ('SID,serial#');

Profiles

Creating the Profile

CREATE PROFILE profile_name LIMITparameter1 valueparameter2 value...;

ALTER USER user_namePROFILE profile_name;

Create the profile as shown setting values for each parameter you want to restrict.

After you create the profile, assign it to the user as shown.

Profile Parameters

Parameter Value Type Description

Sessions_Per_User Integer Number of concurrent session the user is allowed. If the user connects to other Oracle products such as Oracle * Forms, this value should be set to at least 5.

CPU_Per_Session Hundredths of a second

Amount of CPU time used per session.

CPU_Per_Call Hundredths of a second

Amount of CPU time used per single SQL request.

Logical_Reads_Per_Session

Number ofDB Bocks

Number of blocks that can be read during a session.

Logical_Reads_Per_Call

Number ofDB Blocks

Number of blocks that can be read with a single SQL request.

Profile Parameters (cont.)

Parameter Value Type Description

Idle_Time Minutes If the user doesn’t enter something into SQL for this amount of time, the session will be terminated.

Connect_Time Minutes Amount of time the user may be connected to the database during a 24 hour period.

Private_SGA_Per_Session

Number ofDB Blocks

Limits the size of the private memory that can be used for storing a user’s private SQL.

Composite_Limit Integer A composite of the parameters underlined. Even though no individual resource limit is reached, Composite_Limit can impose a limit on the total of the resources used. Set a resource value for each parameter using ALTER RESOURCECOST. For Example, ALTER RESOURCE COST Connect_Time 10; Each minute of connect time will generate a resource use of 10. Set the resource limit for all other parameters. Provide a value for the Composite_Limit.

Example of CREATE PROFILE

SQL> Create Profile USER_PROFILE Limit2 Idle_Time 103 CPU_Per_Session 10004 Logical_Reads_Per_Call 20;

Use the ALTER PROFILE statement to modify an existing profile.

SQL> Alter Profile USER_PROFILE Limit2 Sessions_Per_User 10;

Profile altered.

User logged off if no activity for 10 minutes.10 seconds of CPU time allowed.

Max of 20 blocks retrieved with a single SQL statement.

User may be logged on up to 10 times

Assign a Profile to a User

SQL> alter user jerry2 profile USER_PROFILE;

User altered.

SQL> create user john...

8 profile USER_PROFILE;User created.

Add the profile to the definition of an existing user.

Once the profile has been created, add it to the definition of a new user.

View Profile ParametersSQL> Select * From DBA_Profiles2 Where Resource_Type = 'KERNEL'3 Order By 1;

PROFILE RESOURCE_NAME RESOURCE LIMIT--------------- --------------------------- -------- ---------DEFAULT COMPOSITE_LIMIT KERNEL UNLIMITED DEFAULT SESSIONS_PER_USER KERNEL UNLIMITED DEFAULT CPU_PER_CALL KERNEL UNLIMITED DEFAULT LOGICAL_READS_PER_CALL KERNEL UNLIMITED DEFAULT CONNECT_TIME KERNEL UNLIMITED DEFAULT PRIVATE_SGA KERNEL UNLIMITED DEFAULT IDLE_TIME KERNEL UNLIMITED DEFAULT LOGICAL_READS_PER_SESSION KERNEL UNLIMITED DEFAULT CPU_PER_SESSION KERNEL UNLIMITED

View Profile Parameters (cont.)

PROFILE RESOURCE_NAME RESOURCE LIMIT--------------- --------------------------- -------- ---------

USER_PROFILE COMPOSITE_LIMIT KERNEL DEFAULT USER_PROFILE PRIVATE_SGA KERNEL DEFAULT USER_PROFILE SESSIONS_PER_USER KERNEL 10USER_PROFILE CPU_PER_CALL KERNEL DEFAULT USER_PROFILE LOGICAL_READS_PER_CALL KERNEL 20USER_PROFILE CONNECT_TIME KERNEL DEFAULT USER_PROFILE IDLE_TIME KERNEL 10USER_PROFILE LOGICAL_READS_PER_SESSION KERNEL DEFAULT USER_PROFILE CPU_PER_SESSION KERNEL 1000

Managing Segments

Overwriting Default Storage Parameters

SQL> Create Table Emp2 (ID Number(3) Primary Key,3 Name Varchar2(20) Not Null,4 Salary Number(6) Not Null,5 Dept Char(3),6 Hiredate Date Not Null)7 Tablespace Data8 Storage(9 Minextents 1 PctIncrease 50);

Table created.

Setting Storage Parameters

SQL> Create Table DEPARTMENT2 (Dept Char(3) Primary Key,3 DeptName Varchar2(40))4 Tablespace DATA25 Storage(6 Initial 48K);

Table created.

SQL> Create Index EMP_DEPT_IDX2 On EMP(Dept)3 Tablespace INDEXES;

Index created.

Change the initial storage on a locally managed tablespace with uniform extent sizes of 32K. The initial storage will be two extents (or 64K).

Place an index in the INDEXES tablespace.

Data Block Storage ConceptsConcept Value Type Description

PctUsed Integer the percentage of the space in a block that forms a lower threshold necessary for adding data to the block. The default value for this parameter is 40 and may be changed when the table is created.

PctFree Integer the percent of the space in the block that will be left unused when the data for rows are placed in the block. The default value for this parameter is 10 and may be changed by when the table is created. This parameter should not be set to value exceeding 20.

FreeList N/A a list of block ids indicating the blocks that are available to accept data. New rows inserted into the table may now be placed in the block until the block fills as it did originally.

Overhead Integer bytes used by the database to establish pointers to the data in the block.

Storage in a Data Block

PctUsed

PctFreeOverhead

Oracle Data Block

Row

are

add

ed fi

lling

the

data

blo

ck to

the

leve

l sho

wn

Space used by Oracle for row pointersAdditional data added to existing rows may be stored in this part of the data block.

New rows will not be added to the data block until the data in the block falls to the level shown.

Set PctFree high if the data in the table change frequently.

Set PctFree low if the data in the table are stable.

Migration and Chaining

Concept DescriptionMigration occurs when there is not enough space remaining in a

block to accommodate updates to the data in a block. This may occur because a null value is changed to an actual value or data are added to a variable with a varchar2 data type. If space is not available, the entire row must be relocated to another data block.

Chaining the length of rows in a table exceed the length of the database block size forcing the row to be stored over more than one block. The database block size may not be changed once the database has been created. The only solution to preventing chaining is to recreate the database with a larger block size.

Modifying PctFree and PctUsed

SQL> Create Table CUSTOMER2 (CID Char(2) Primary Key,3 CName Varchar2(20) Not Null,4 Region Char(1),5 ID Number(3))6 Tablespace DATA7 Storage(8 Initial 64K)9 PctFree 15 PctUsed 50;

The SQL statement below adds a new PctFree and PctUsed value to a new table. Note that the PctFree and PctUsed are not part of the Storage clause.

Gathering Segment Statistics

The Analyze Table Statement

• Oracle will use the Cost-Based (generally more efficient) optimizer if the tables are analyzed.

• Identify chained and migrated rows.

• Validate the structure of the table or index (i.e. check the integrity of the data).

Analyzing a table (or index) allows you to collect statistics on that table. The statistics may be viewed through views of the data dictionary including the user_tables view. You should Analyze Table for the following reasons.

Columns Populated by Analyze Table.(from User_Tables)

SQL> Desc User_Tables

Name Null? Type -------------------------- ----- ------NUM_ROWS NUMBERBLOCKS NUMBEREMPTY_BLOCKS NUMBERAVG_SPACE NUMBERCHAIN_CNT NUMBERAVG_ROW_LEN NUMBERAVG_SPACE_FREELIST_BLOCKS NUMBERNUM_FREELIST_BLOCKS NUMBERSAMPLE_SIZE NUMBERLAST_ANALYZED DATE

A partial display of the User_Tables view shows the columns populated by the Analyze Tablestatement.

Columns Populated by Analyze Table(from User_Tab_Col_Statistics)

SQL> desc user_tab_col_statisticsName Null? Type ------------- -------- ------------TABLE_NAME NOT NULL VARCHAR2(30)COLUMN_NAME NOT NULL VARCHAR2(30)NUM_DISTINCT NUMBERLOW_VALUE RAW(32)HIGH_VALUE RAW(32)DENSITY NUMBERNUM_NULLS NUMBERNUM_BUCKETS NUMBERLAST_ANALYZED DATESAMPLE_SIZE NUMBERGLOBAL_STATS VARCHAR2(3)USER_STATS VARCHAR2(3)AVG_COL_LEN NUMBER

The columns retrieved from the view User_Tab_Col_Statistics are populated with the Analyze Tablestatement.

Computing Statistics

TABLE_NAME LAST_ANAL NUM_ROWS BLOCKS EMPTY_BLOCKS AVG_SPACE AVG_ROW_LEN---------- --------- ---------- ---------- ------------ ---------- -----------CUSTOMER

SQL> Col Table_Name Format a10;SQL> Select Table_Name,

2 Last_Analyzed,3 Num_Rows,4 Blocks,5 Empty_Blocks,6 Avg_Space,7 Avg_Row_Len8 From User_Tables;

The query on the left shows that no statistics exist in the CUSTOMER table.

Analyze Table

TABLE_NAME LAST_ANAL NUM_ROWS BLOCKS EMPTY_BLOCKS AVG_SPACE AVG_ROW_LEN---------- --------- ---------- ---------- ------------ ---------- -----------CUSTOMER 06-JUN-15 5 1 1 8012 16

SQL> Col Table_Name Format a10;SQL> Select Table_Name,

2 Last_Analyzed,3 Num_Rows,4 Blocks,5 Empty_Blocks,6 Avg_Space,7 Avg_Row_Len8 From User_Tables

The query on the left retrieves the results of the ANALYZE TABLE statement.

SQL> Analyze Table CUSTOMER2 Compute Statistics;

Table analyzed.

Analyze the CUSTOMER table to generate statistics.

Viewing Column Statistics

TABLE_NAM COL_NAM NUM_DIS NUM_NU AVG_CO LAST_ANAL--------- ------- ------- ------ ------- ----------CUSTOMER CID 5 0 2 06-JUN-15CUSTOMER CNAME 5 0 5 06-JUN-15CUSTOMER REGION 2 1 1 06-JUN-15CUSTOMER ID 3 1 3 06-JUN-15

SQL> Col Table_Name Format a10;SQL> Col Col_Name Format a10;

SQL> Select Table_Name,2 Column_Name,3 Num_Distinct,4 Num_Nulls,5 Avg_Col_Len,6 Last Analyzed8 From User_Tab_Col_Statistics;

The query on the left retrieves the data on the columns.

Estimating Statistics

SQL> Analyze Table DEPARTMENT2 Estimate Statistics;

Table analyzed.

If you Estimate Statistics, a random sample of up to 1,064 rows will be used by default.

SQL> Connect Jerry/WelcomeConnected.

SQL> Analyze Table EMP2 Estimate Statistics3 Sample 40 Percent;

Table analyzed.

You can specify a sample size by supplying a percent or a number of rows. Regardless of how specified, if the number of rows in the sample exceeds 50 percent of the rows in the table, ALL the rows will be used.

Viewing Estimated Statistics

TABLE_NAME LAST_ANAL NUM_ROWS BLOCKS EMPTY_BLOCKS AVG_SPACE AVG_ROW_LEN---------- --------- ---------- ---------- ------------ ---------- -----------DEPARTMENT 06-JUN-15 3 1 2 8025 24DEPARTMENT 06-JUN-15 8 1 0 7880 26

SQL> Col Table_Name Format a10;SQL> Select Table_Name,

2 Last_Analyzed,3 Num_Rows,4 Blocks,5 Empty_Blocks,6 Avg_Space,7 Avg_Row_Len8 From User_Tables

The query on the left retrieves the results of the ANALYZE TABLE statement.

Validate Structure

SQL> Analyze Table EMP2 Validate Structure;

Table analyzed.

SQL> Analyze Table DEPARTMENT2 Validate Structure3 Cascade;

Table analyzed.

The statement on the right will validate the integrity of the blocks used by EMP.

The statement on the right validates the structure of DEPARTMENT and of all objects associated with DEPARTMENT such as indexes written on the table.

Useful Data Dictionary

Views

Viewing Table ParametersSQL> select owner, table_name, tablespace_name,

2 pct_free, pct_used, ini_trans, max_trans,3 initial_extent, next_extent, min_extents,4 max_extents, pct_increase5 from dba_tables6 where owner not in ('SYS','SYSTEM');

TABLE TABLESPACE PCT PCT INI MAX INITIAL NEXT MIN MAX PCTOWNER NAME NAME FREE USED TRANS TRANS EXTENT EXTENT EXTENTS EXTENTS INCREASE------- ----------- ---------- ---- ----- ---- ----- -------- ------ ------- ------- --------OUTLN OL$ SYSTEM 10 40 1 255 16384 16384 1 505 50OUTLN OL$HINTS SYSTEM 10 40 1 255 16384 16384 1 505 50JERRY EMP DATA 10 40 1 255 32768 32768 1 121 50JERRY DEPARTMENT DATA2 10 40 1 255 49152 32768 1 2147483645 0ELAINE CUSTOMER DATA 15 50 1 255 32768 40960 2 121 255 rows selected.

Viewing Information on QuotasSQL> Select * From DBA_TS_Quotas Order By Username;

(A Max_Bytes value equal to -1 indicates the quota is unlimited.)

TABLESPACE_NAME USERNAME BYTES MAX_BYTES BLOCKS MAX_BLOCKS--------------- -------- ------- ---------- ------- ----------DATA ELAINE 131072 5242880 16 640INDEXES ELAINE 65536 -1 8 -1DATA2 ELAINE 0 10485760 0 1280TEMP ELAINE 0 -1 0 -1DATA GEORGE 0 5242880 0 640TEMP GEORGE 0 -1 0 -1INDEXES JERRY 65536 -1 8 -1DATA JERRY 98304 5242880 12 640DATA2 JERRY 98304 10485760 12 1280TEMP JERRY 0 -1 0 -1DATA KRAMER 0 5242880 0 640TEMP SUPERMAN 0 -1 0 -1DATA SUPERMAN 0 5242880 0 64013 rows selected.

Quotas by TablespaceSQL> Select Tablespace_Name,

2 SUM(Bytes) As Bytesused3 SUM(Blocks) As Blocksused4 From DBA_TS_Quotas5 Group By Tablespace_Name;

TABLESPACE_NAME BYTESUSED BLOCKSUSED--------------- ---------- -----------DATA 229376 28DATA2 98304 12INDEXES 131072 16TEMP 0 04 rows selected.

Monitoring Space UsageSQL> Select a.Tablespace_Name,2 SUM(a.Bytes) As BytesFree,3 SUM(b.Bytes) As BytesUsed,4 SUM(b.Bytes)/(SUM(a.Bytes)+SUM(b.Bytes)) * 1005 As "Percent Used"6 From DBA_Free_Space a, DBA_TS_Quotas b7 Where a.Tablespace_Name = b.Tablespace_Name8 Group By a.Tablespace_Name;

TABLESPACE_NAME BYTESFREE BYTESUSED Percent Used------------------------ ---------- ---------- ------------DATA 30228480 688128 2.2257552DATA2 12124160 196608 1.5957447INDEXES 8093696 262144 3.1372549TEMP 41910272 0 0

Viewing Information on SegmentsSQL> Select Owner, Segment_Type, Tablespace_Name,

2 Segment_Name, Extents, Max_Extents3 From DBA_Segments4 Where Tablespace_Name NOT IN ('SYSTEM', 'TOOLS')5 Order By Owner;

OWNER SEGMENT_TYPE TABLESPACE_NAME SEGMENT_NAME EXTENTS MAX_EXTENTS------- ------------- --------------- ------------- ------- -----------ELAINE TABLE DATA CUSTOMER 2 121ELAINE INDEX DATA SYS_C001043 2 121ELAINE INDEX INDEXES CUST_REGION_IDX 2 121JERRY TABLE DATA EMP 1 121JERRY TABLE DATA2 DEPARTMENT 2 2147483645JERRY INDEX DATA SYS_C001033 2 121JERRY INDEX INDEXES EMP_DEPT_IDX 2 121JERRY INDEX DATA2 SYS_C001034 1 2147483645SYS ROLLBACK RBS RBS0 8 40969 rows selected.

Segment Information by Tablespace

SQL> select tablespace_name,2 count(*) as segments,3 sum(bytes) as bytes4 from dba_segments5 group by tablespace_name;

TABLESPACE_NAME SEGMENTS BYTES------------------------------ ---------- ----------DATA 4 262144DATA2 2 65536INDEXES 2 131072RBS 1 4194304SYSTEM 445 570900486 rows selected.

Segment Information by OwnerSQL> Select Owner,2 Count(*) As Segments,3 Sum(Bytes) As Bytes4 From DBA_Segments5 Group By Owner;

OWNER SEGMENTS BYTES------------------ ---------- ----------ELAINE 3 196608JERRY 5 262144OUTLN 5 81920SYS 389 57794560SYSTEM 52 3407872

Segment Information by Type

SQL> Select Segment_Type,2 Count(*) As Segments,3 Sum(Bytes) As Bytes4 From DBA_Segments5 Group By Segment_Type;

SEGMENT_TYPE SEGMENTS BYTES------------------ ---------- ----------CACHE 1 8192CLUSTER 9 2940928INDEX 239 19488768LOBINDEX 13 655360LOBSEGMENT 13 688128ROLLBACK 2 5029888TABLE 177 32931840

Viewing Information on ExtentsSQL> Select Owner, Segment_Name, Segment_Type,

2 Tablespace_Name, Extent_Id, Bytes3 From DBA_Extents4 Where Tablespace_Name != 'SYSTEM'5 Order By Owner, Segment_Name;

SEGMENT_ TABLESPACE EXTENTOWNER SEGMENT_NAME TYPE _NAME _ID BYTES BLOCKS-------- --------------- --------- ---------- ------- ------- -------ELAINE CUSTOMER TABLE DATA 0 32768 4ELAINE CUSTOMER TABLE DATA 1 32768 4ELAINE CUST_REGION_IDX INDEX INDEXES 0 32768 4ELAINE CUST_REGION_IDX INDEX INDEXES 1 32768 4ELAINE SYS_C001043 INDEX DATA 1 32768 4ELAINE SYS_C001043 INDEX DATA 0 32768 4JERRY EMP TABLE DATA 0 32768 4JERRY SYS_C001054 INDEX DATA 1 32768 4JERRY DEPARTMENT TABLE DATA2 0 32768 4JERRY DEPARTMENT TABLE DATA2 1 32768 4JERRY EMP_DEPT_IDX INDEX INDEXES 0 32768 4JERRY EMP_DEPT_IDX INDEX INDEXES 1 32768 4

Extents and Their Data FilesSQL> Select Owner, Segment_Name, Extent_ID,2 Segment_Type,File_Name3 From DBA_Extents a, DBA_Data_Files b4 Where a.File_ID = b.File_ID5 And a.Tablespace_Name != 'SYSTEM'6 Order By Owner, Segment_Type;

EXTENT SEGMENTOWNER SEGMENT_NAME _ID _TYPE FILE_NAME--------- --------------- ------ --------- ---------------------------------------ELAINE CUSTOMER 1 TABLE /oraclec/data/DB08/Disk1/data01.dbf ELAINE CUSTOMER 0 TABLE /oraclec/data/DB08/Disk1/data01.dbf ELAINE SYS_C001043 1 INDEX /oraclec/data/DB08/Disk1/data01.dbf ELAINE SYS_C001043 0 INDEX /oraclec/data/DB08/Disk1/data01.dbfELAINE CUST_REGION_IDX 1 INDEX /oraclec/data/DB08/Disk3/indexes01.dbf ELAINE CUST_REGION_IDX 0 INDEX /oraclec/data/DB08/Disk4/indexes02.dbf JERRY EMP 0 TABLE /oraclec/data/DB08/Disk1/data01.dbf JERRY DEPARTMENT 0 TABLE /oraclec/data/DB08/Disk1/data201.dbf JERRY DEPARTMENT 1 TABLE /oraclec/data/DB08/Disk2/data202.dbf JERRY EMP_DEPT_IDX 0 INDEX /oraclec/data/DB08/Disk3/indexes01.dbfJERRY EMP_DEPT_IDX 1 INDEX /oraclec/data/DB08/Disk4/indexes02.dbfJERRY SYS_C001054 0 INDEX /oraclec/data/DB08/Disk1/data01.dbfJERRY SYS_C001054 1 INDEX /oraclec/data/DB08/Disk1/data02.dbf JERRY SYS_C001055 0 INDEX /oraclec/data/DB08/Disk1/data201.dbf

Viewing Information on ObjectsSQL> Select Owner, Object_Name, Object_Type,

2 Created, Last_DDL_Time3 From DBA_Objects4 Where Owner Not In5 ('SYS','SYSTEM','PUBLIC','OUTLN','DBSNMP')

OWNER OBJECT_NAME OBJECT_TYPE CREATED LAST DDL_TIME------- ---------------- ----------- ---------- -------------JERRY DEPARTMENT TABLE 06-JUN-15 06-JUN-15JERRY EMP TABLE 06-JUN-15 06-JUN-15JERRY EMP_DEPT_IDX INDEX 06-JUN-15 06-JUN-15JERRY EMP_DEPT_SAL VIEW 06-JUN-15 06-JUN-15JERRY EMP_SALARY VIEW 01-JUN-15 01-JUN-15JERRY SYS_C00996 INDEX 06-JUN-15 06-JUN-15JERRY SYS_C00997 INDEX 06-JUN-15 06-JUN-15ELAINE CUSTOMER TABLE 06-JUN-15 06-JUN-15ELAINE CUST_REGION_IDX INDEX 06-JUN-15 06-JUN-15ELAINE SYS_C001001 INDEX 06-JUN-15 06-JUN-15

Modifying ParametersSQL> Alter Table EMP

2 Storage (Next 16K3 PctIncrease 40)4 PctUsed 60;

Table altered.

SQL> Alter Table EMP2 Deallocate Unused;

Table altered.

SQL> Alter Table EMP2 Deallocate Unused3 Keep 24K;

Table altered.

Modify the storage parameters of an existing table. The new parameters will apply to all subsequently created extents. Existing extents will not be affected.

Deallocating unused extents frees the extents allocated to the table but not used.

Deallocate unused extents keeping 24K of unused space allocated to the table.

Allocating New Extents

SQL> Alter Table CUSTOMER Allocate Extent;Table altered.

SQL> Alter Table EMP2 Allocate Extent3 (Size 16K Datafile4 '/oraclec/data/DB08/Disk2/data02.dbf');Table altered.

Force the allocation of a new extent. The extent will be sized according to the parameters in effect.

Create an extent of a specified size on a specified disk.

Removing TablesSQL> Drop Table EMP;Table dropped.

SQL> Drop Table EMP;Drop Table EMP

*ERROR at line 1:ORA-02449: unique/primary keys intable referenced by foreign keys

SQL> Drop Table EMP2 Cascade Constraints;

Table dropped.

SQL> Drop Table Elaine.CUSTOMER;Table dropped.

Drop the table with the statement on the right

If the table is referenced in a foreign key constraint by another table, you will receive the error shown on the right.

Use the statement on the right if you want to drop the foreign key constraints as well as the table.

If you have the DBA privileges, you can drop another user’s table.