SlideShare a Scribd company logo
1 of 61
Download to read offline
SQL For DBAs
Developers and Users will learn
something as well!

              Daniel W. Fink
Overview
♦ Where is the information
  – Data Dictionary views & tables
♦ How can I extract it?
  – SQL, functions
♦ How can I use it?
  – SQL*Plus to build and execute the script
Method
♦ Build a script that generates the ‘create
  tablespace’ commands for the database
♦ Not all options considered
   –   AUTOEXTEND
   –   MINEXTENT
   –   ONLINE/OFFLINE
   –   *I have to leave something for you to add…
♦ Not all tablespaces
  – Enough to demonstrate likely permutations
Command
♦ Rules
  – Tablespace can be TEMPORARY
  – TEMPORARY tablespace can use DATA files
    or TEMP files
  – A single tablespace can have multiple data files
♦ Command structure
   CREATE [TEMPORARY] TABLESPACE tablespacename
   [TEMPORARY]
   {DATAFILE|TEMPFILE} filename filesize
   EXTENT MANAGEMENT [DICTIONARY|LOCAL
        [{AUTOALLOCATE|UNIFORM} [size {K|M}]]}]
Oracle’s Data Dictionary
♦ Access via Views
  – 1390 in 8i
  – 1820 in 9i
♦ DBA_ - Everything in database
♦ ALL_ - What you can see
♦ USER_ What you own
♦ Other – Miscellaneous views
Where does it come from?
♦ Views of underlying base objects
♦ Provides level of abstraction
   – Easy to understand
   – Hides translations and calculations
   – READ ONLY!
Columns                                    View Text
TABLESPACE_NAME     select ts.name,
INITIAL_EXTENT         ts.blocksize * ts.dflinit,
NEXT_EXTENT            decode(bitand(ts.flags, 3), 1, to_number(NULL),
                               ts.blocksize*ts.dflincr),
MIN_EXTENTS            ts.dflminext,
MAX_EXTENTS            decode(ts.contents$, 1, to_number(NULL), ts.dflmaxext),
PCT_INCREASE           decode(bitand(ts.flags, 3), 1, to_number(NULL),
                              ts.dflextpct),
MIN_EXTLEN             ts.blocksize * ts.dflminlen,
STATUS                 decode(ts.online$,1,'ONLINE',2,'OFFLINE',
                              4,'READ ONLY','UNDEFINED'),
CONTENTS               decode(ts.contents$, 0, 'PERMANENT', 1, 'TEMPORARY'),
LOGGING                decode(ts.dflogging, 0, 'NOLOGGING', 1, 'LOGGING'),
EXTENT_MANAGEMENT      decode(ts.bitmapped, 0, 'DICTIONARY', 'LOCAL'),
ALLOCATION_TYPE        decode(bitand(ts.flags,3),0,'USER',1,'SYSTEM',2,'UNIFORM',
                              'UNDEFINED'),
PLUGGED_IN             decode(ts.plugged, 0, 'NO', 'YES')
                    from sys.ts$ ts
                    where ts.online$ != 3
Where can I find more
information?
♦ Oracle Documentation – Server Reference
  Guide
♦ DBA_VIEWS
  – text contains the actual text of the view
  – SET LONG 10000 in order to see all the text
♦ catalog.sql
♦ sql.bsq
Notes on Data Dictionary
♦ ID
   – COLUMN_ID starts at 1
   – EXTENT_ID starts at 0
♦ Not All DBA_* views have ALL_* and/or USER_*
  counterparts
♦ DBA_EXTENTS and USER_EXTENTS have different
  information
   – USER_EXTENTS does not contain file information
♦ DBA_TAB_COLUMNS
   – Not just table columns, also views, clusters
♦ DBA_IND_COLUMNS
   – Reverse Key Indexes have function name instead of table column
     name for leading column
Quick Tour of the Data
Dictionary

Tables/Views             Indexes                 Storage
DBA_TABLES               DBA_INDEXES             DBA_TABLESPACES
DBA_TAB_COLUMNS          DBA_IND_COLUMNS         DBA_DATA_FILES
DBA_TAB_COL_STATISTICS   DBA_IND_PARTITIONS      DBA_TEMP_FILES
DBA_TAB_HISTOGRAMS       DBA_IND_SUBPARTITIONS   DBA_SEGMENTS
DBA_PART_TABLES          DBA_PART_INDEXES        DBA_EXTENTS
DBA_TAB_PARTITIONS                               DBA_ROLLBACK_SEGS
DBA_TAB_SUBPARTITIONS
                         Users                   DBA_FREE_SPACE
DBA_CONSTRAINTS          DBA_USERS

DBA_CONS_COLUMNS         DBA_ROLES

DBA_VIEWS                DBA_ROLE_PRIVS
                         DBA_TAB_PRIVS
                         DBA_SYS_PRIVS
                         DBA_PROFILES
Data Dictionary views for script
♦ DBA_TABLESPACES
  – All tablespaces in database
♦ DBA_DATAFILES
  – All DATAFILEs for all tablespaces
♦ DBA_TEMPFILES
  – *New in Oracle 8i
  – Identifies TEMPFILES created by command
    “create temporary tablespace”
Using SQL to Write SQL
♦ Joins
♦ Unions
♦ Functions
♦ Sorting
Joins
♦ A relationship using common data (natural or
  derived) must exist
♦ Inner
   – If a related row exists, return both main and related row
   – If a related row does not exist, do not return the main
     row
♦ Outer
  – If a related row exists, return both main and related row
  – If a related row does not exist, return main row and null
    values for related row
Join
select t.tablespace_name,
       d.file_name
from dba_tablespaces t,
     dba_data_files d
where d.tablespace_name = t.tablespace_name;

TABLESPACE_NAME   FILE_NAME
---------------   ---------------------------------
SYSTEM            C:ORADATAORA817SYSTEM01.DBF
TOOLS             C:ORADATAORA817TOOLS01.DBF
TOOLS             C:ORADATAORA817TOOLS02.DBF
TEMP2             C:ORADATAORA817TEMP201.DBF
Union
♦ Set Operation
♦ Used to combine sets of data
   – Joins & Relationships are not used
♦ Columns must be same number and datatype
   – A literal expression can be used
♦ Returns one row for each distinct set of values
   – UNION ALL will return duplicates

   select statement1
   union
   select statement2
File List
♦ File names are listed in
   – DBA_DATA_FILES (10 rows)
   – DBA_TEMP_FILES (1 row)
♦ Common Data?
  – Both contain tablespace_name…
File List
select d.file_name, t.file_name
from dba_data_files d,
     dba_temp_files t
where d.tablespace_name = t.tablespace_name;

no rows selected

♦ Why?
  – Tablespaces use either data files or temp
    files…not both
  – Even an outer join will miss rows
File List

                       FILE_NAME
select file_name       ------------------------------
from dba_data_files    C:ORADATAORA817RBS01.DBF
                       C:ORADATAORA817SYSTEM01.DBF
union                  C:ORADATAORA817TEMP01.DBF
                       C:ORADATAORA817TEMP201.DBF
select file_name       C:ORADATAORA817TOOLS01.DBF
from dba_temp_files;   C:ORADATAORA817TOOLS02.DBF
Tablespace/File List

select tablespace_name   TABLESPACE_NAME
                         ------------------------------------
from dba_tablespaces     C:ORADATAORA817SYSTEM01.DBF
union                    C:ORADATAORA817TEMP01.DBF
                         C:ORADATAORA817TEMP201.DBF
select file_name         C:ORADATAORA817TOOLS01.DBF
from dba_data_files      C:ORADATAORA817TOOLS02.DBF
                         SYSTEM
union
                         TEMP
select file_name         TEMP2
from dba_temp_files;     TOOLS
Functions
♦ Concatenation
   – Combine 2 or more strings together
♦ DECODE/CASE
   – Conditional display/decision-making
♦ TO_CHAR
   – Converts a number or date to a character string
♦ CHR
   – Displays the ASCII character
♦ ASCII
   – Displays the ASCII number
Concatenation
♦ Combine two or more strings together
  – Remember to add blanks
♦ CREATE TABLESPACE <ts_name>
  CONCAT(‘CREATE TABLESPACE ’,
    tablespace_name)
  ‘CREATE TABLESPACE ’||tablespace_name
DECODE/CASE
♦ Rudimentary decision making function
♦ DECODE available in 7/8/9
♦ CASE available from 8.1.6+
♦ Use to determine
  – Type of tablespace
  – Extent Management
  – Datafile separation
DECODE
♦ DECODE(expression,
            comparison1, return1,
            comparison2, return2,
            …
            default)
♦ Can only use equality comparison
DECODE
If DBA_TABLESPACES.CONTENTS = ‘TEMPORARY’ display
    ‘TEMPORARY’
ELSE IF DBA_TABLESPACES.CONTENTS = ‘PERMANENT’ display NULL
ELSE display NULL

select ‘CREATE ‘||decode(contents,
                  ‘TEMPORARY’,‘TEMPORARY ’,
                  ‘PERMANENT’,NULL,NULL)||
        ‘TABLESPACE ‘||tablespace_name
from dba_tablespaces;

CREATE   TABLESPACE SYSTEM
CREATE   TEMPORARY TABLESPACE TEMP
CREATE   TEMPORARY TABLESPACE TEMP2
CREATE   TABLESPACE TOOLS
CASE
♦ Introduced in 8.1.6
♦ Able to return based on variable conditions

CASE WHEN condition1 THEN result1
     WHEN condition2 THEN result2
    …
    ELSE default
CASE
select ‘CREATE ‘||
        CASE WHEN contents=‘TEMPORARY’ THEN ‘TEMPORARY ’
             WHEN contents=‘PERMANENT’ THEN NULL
             ELSE NULL
         END||’TABLESPACE ‘||tablespace_name
from dba_tablespaces;


CREATE   TABLESPACE SYSTEM
CREATE   TEMPORARY TABLESPACE TEMP
CREATE   TEMPORARY TABLESPACE TEMP2
CREATE   TABLESPACE TOOLS
♦ Permanent = NULL not currently needed, but
  included for example
Character String Conversion
♦ TO_CHAR([date|number]{,format string})
   – Converts numbers or dates to character string
   – Uses format codes to change display
♦ TO_CHAR(number)
   – Does not require format string
   – Oracle will also convert numeric string to number
   – If you are not formatting, Oracle will automatically
     convert to string…UNLESS it is used in a UNION
Character String Conversion
select 12345||’ is a number’ from dual;
  12334 is a number

select ‘12345’-10 from dual;
   12335

select 12345 from dual
union
select ‘is a number’ from dual;
ORA-01790: expression must have same datatype as
  corresponding expression
CHR
♦ CHR is used to ‘print’ special characters
  – CHR(<ascii_number>)
♦ ASCII can be used to determine the number
  of the character
  – ASCII(‘<character>’)
Single Tic
♦ Data files in statement must be enclosed in single
  tic (‘)
   – ‘ is a character and can be enclosed in ‘ as a character
     string
   – but I can never remember how many I need
       (I think it’s 4…or is it 3…What if I am using it to end a string?)
♦ CHR(39) prints a single ‘
Single Tic
  SQL> select chr(39)||file_name||chr(39)
    2 from dba_data_files;

  'C:ORADATAORA817SYSTEM01.DBF'
  'C:ORADATAORA817TOOLS01.DBF'




  SQL> select ’’’’||file_name||’’’’
    2 from dba_data_files;

  'C:ORADATAORA817SYSTEM01.DBF'
  'C:ORADATAORA817TOOLS01.DBF'
New Line
♦ CHR(10) ‘prints’ a newline character
  – Able to output single row of data on multiple lines

   select ‘Line 1’||chr(10)||’Line 2’
   from dual;

   Line 1
   Line 2
CREATE TABLESPACE
select ‘CREATE TABLESPACE ‘||
       t.tablespace_name||chr(10)||
       ‘DATAFILE ‘||chr(39)||
       d.file_name||chr(39)
from dba_tablespaces t,
        dba_data_files d
where d.tablespace_name = t.tablespace_name;
CREATE TABLESPACE Error
CREATE TABLESPACE SYSTEM
DATAFILE 'C:ORADATAORA817SYSTEM01.DBF'

CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS01.DBF'

CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS02.DBF'

CREATE TABLESPACE TEMP2
DATAFILE 'C:ORADATAORA817TEMP201.DBF‘


♦ 2nd ‘CREATE TABLESPACE TOOLS’ statement will fail…
   how do we work around?
UNION
♦ UNION of DBA_TABLESPACES,
  DBA_DATA_FILES, DBA_TEMP_FILES
♦ Each SQL statement is executed
  independently, then the results are
  combined
♦ Output will be sorted, in column order
♦ ORDER BY must be last line
UNION
select 'CREATE '||decode(contents, 'TEMPORARY', 'TEMPORARY ', NULL)||
       ’TABLESPACE ‘||tablespace_name
from dba_tablespaces
union
select 'DATAFILE '||chr(39)||file_name||chr(39)||' SIZE
   '||to_char(bytes/1024)||'K'
from dba_data_files
union
select 'TEMPFILE '||chr(39)||file_name||chr(39)||' SIZE
   '||to_char(bytes/1024)||'K'
from dba_temp_files;

CREATE TABLESPACE SYSTEM
CREATE TEMPORARY TABLESPACE TEMP
CREATE TEMPORARY TABLESPACE TEMP2
CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K
DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
Errata
♦ Tablespace to File relationship correct, but not in
  proper order for SQL statement
   – Proper order of lines in command is missing
   – We will use columns to sort…but suppress the printing
♦ Still missing storage/extent management clauses…
   – Later addition…don’t want to clutter up the statements
     just yet
♦ Statement contains an error
SQL*Plus Commands
♦ COLUMN
  – noprint
♦ SET
   – sqlprompt
   – pagesize
   – feedback
COLUMN
♦ The CREATE TABLESPACE line needs to
  be associated with DATAFILE line
♦ COLUMN command can be used to
  suppress printing
  – COLUMN column_name NOPRINT
  – Size of column will be factored in to
    LINESIZE
COLUMN
select tablespace_name ts_name,'CREATE '||
        decode(contents, 'TEMPORARY', 'TEMPORARY ',
                NULL)||’TABLESPACE ‘||tablespace_name
sql_command
from dba_tablespaces
union
select tablespace_name ts_name, 'DATAFILE '||chr(39)||
        file_name||chr(39)||' SIZE '||
        to_char(bytes/1024)||'K' sql_command
from dba_data_files
union
select tablespace_name ts_name,'TEMPFILE '||chr(39)||file_name
      ||chr(39)||' SIZE '||to_char(bytes/1024)||'K' sql_command
from dba_temp_files;
COLUMN

TS_NAME   SQL_COMMAND
-------   -------------------------------------------------------
SYSTEM    CREATE TABLESPACE SYSTEM
SYSTEM    DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K
TEMP      CREATE TEMPORARY TABLESPACE TEMP
TEMP      TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
TEMP2     CREATE TEMPORARY TABLESPACE TEMP2
TEMP2     DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
TOOLS     CREATE TABLESPACE TOOLS
TOOLS     DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
TOOLS     DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
COLUMN Formatting
SQL> COLUMN ts_name NOPRINT
SQL> /
SQL_COMMAND
-------------------------------------------------------
CREATE TABLESPACE SYSTEM
DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K
CREATE TEMPORARY TABLESPACE TEMP
TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
CREATE TEMPORARY TABLESPACE TEMP2
DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
Formatting Output
♦ Supress all non-sql statement strings
♦ SET
   – PAGESIZE 0 – suppress all breaks, headings,
     etc.
   – FEEDBACK OFF – suppress ’10 Rows
     Returned’ message
   – SQLPROMPT “” – removes SQL> prompt
      • Be careful…it may look like the command hangs
Formatting Output
SQL> col ts_name noprint
SQL> set pagesize 0 feedback off sqlprompt ""
/
CREATE TABLESPACE SYSTEM
DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K
CREATE TEMPORARY TABLESPACE TEMP
TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
CREATE TEMPORARY TABLESPACE TEMP2
DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
OOPS
♦ DBA_TABLESPACES.CONTENTS lists
   contents, but not type of file…
  – Each command creates a TEMPORARY
    tablespace, but the file specs are not the same!
  CREATE TABLESPACE TEMPORARY <name> TEMPFILE <name> <specs>
  CREATE TABLESPACE <name> TEMPORARY DATAFILE <name> <specs>

♦ Multiple data or temp files must be
   separated by a comma
Proper Syntax for TEMPORARY
select tablespace_name ts_name,
       'CREATE TABLESPACE '||tablespace_name||
        decode(contents,'TEMPORARY',' TEMPORARY',NULL) sql_command
from dba_tablespaces
where tablespace_name in (select tablespace_name from dba_data_files)
union
select tablespace_name ts_name,
       'CREATE '||decode(contents,'TEMPORARY','TEMPORARY ',NULL)||
          ’TABLESPACE ‘|| tablespace_name sql_command
from dba_tablespaces
where tablespace_name in (select tablespace_name from dba_temp_files)
union
select tablespace_name ts_name,
       'DATAFILE '||chr(39)||file_name||chr(39)||' SIZE '||
             to_char(bytes/1024)||'K' sql_command
from dba_data_files
union
select tablespace_name ts_name,
       'TEMPFILE '||chr(39)||file_name||chr(39)||' SIZE '||
              to_char(bytes/1024)||'K' sql_command
from dba_temp_files
Proper Syntax for TEMPORARY
CREATE TABLESPACE SYSTEM
DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K
CREATE TEMPORARY TABLESPACE TEMP
TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
CREATE TABLESPACE TEMP2 TEMPORARY
DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
Proper Syntax for Multiple Files
CREATE TABLESPACE <tsname>
DATAFILE <filename> <filespecs>,
 <filename> <filespecs>

♦ Where can the comma go?
  – After the file specs OR
  – Before the next file name
       • Logic easier for 2nd choice
♦ File order is not important
   – Each file has a numeric ID
   – Skip the file with the lowest ID
Proper Syntax for Multiple Files
♦ Add file_id as a column and sort by it
♦ While we are at it…add sql_sort column to
  insure proper order of statements
♦ Current Sort Order
  – tablespace_name
  – ts_sort (each part of union has a new value)
  – sql_sort (file_id or derived value)
Proper Syntax for Multiple Files
select tablespace_name ts_name, 0 ts_sort,   0 sql_sort,
       <create tablespace line>
union
select tablespace_name ts_name, 1 ts_sort,   file_id sql_sort
       <datafile line>
union
select tablespace_name ts_name, 1 ts_sort,   file_id sql_sort
       <tempfile line>
union
select tablespace_name ts_name, 2 ts_sort,   0 sql_sort
       <storage line>
order by ts_name, ts_sort, sql_sort;
Multiple Files
select df.tablespace_name ts_name, 1 ts_sort, file_id
   sql_sort,
       decode(df.file_id,tfi.min_file_id,'DATAFILE ',
               ', ')||chr(39)||df.file_name||chr(39)||
             ' SIZE '||to_char(df.bytes/1024)||'K'
   sql_command
from dba_data_files df,
     (select tablespace_name t_name, min(file_id)
   min_file_id
      from dba_data_files
      group by tablespace_name) tfi
where df.tablespace_name = tfi.t_name
  and tablespace_name != 'SYSTEM'
♦ Because we are sorting on file_id, we know that the ‘first’
  file will be the first displayed
Proper Output (with columns)
TS_NAME TS   SQL    SQL_COMMAND
------- ---- ----- ------------------------------------------------------------
TEMP       0      0 CREATE TEMPORARY TABLESPACE TEMP
TEMP       1      1 TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
TEMP2      0      0 CREATE TABLESPACE TEMP2 TEMPORARY
TEMP2      1      4 DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
TOOLS      0      0 CREATE TABLESPACE TOOLS
TOOLS      1      5 DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
TOOLS      1     10 , 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
Proper Output (without columns)
CREATE TEMPORARY TABLESPACE TEMP
TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
CREATE TABLESPACE TEMP2 TEMPORARY
DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K
CREATE TABLESPACE TOOLS
DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K
, 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
What’s Next?
♦ Extent Management & Storage Clause
   – Dictionary Extent Management is default, no need to
     specify
   – DEFAULT STORAGE and LOCAL extent
     management are mutually exclusive
♦ Interesting notes…
   – Not all Tablespaces have NEXT defined
   – Not all Tablespaces have MAXEXTENTS defined
   – What else may be NULL?
Extent Management & Storage
♦ Extent Management can be
  – LOCAL
    • AUTOALLOCATE
    • UNIFORM SIZE
  – DICTIONARY
    • default…no need to specify
Dictionary Extent Management
CASE WHEN ts.extent_management = 'DICTIONARY'
   THEN 'DEFAULT STORAGE ('||
         decode(ts.initial_extent, NULL, NULL,
          ' INITIAL '||to_char(ts.initial_extent/1024)||'K')||
          decode(ts.next_extent, NULL, NULL,
                 ' NEXT'||to_char(ts.next_extent/1024)||'K')||
          decode(ts.min_extents, NULL, NULL,
                 ' MINEXTENTS '||to_char(ts.min_extents))||
          decode(ts.max_extents, NULL, NULL,
                 ' MAXEXTENTS '||to_char(ts.max_extents))||
          decode(ts.pct_increase, NULL, NULL,
               ' PCTINCREASE'||to_char(ts.pct_increase))||');‘
Local Extent Management
♦    Allocation type and the command are not
    the same!
WHEN ts.extent_management = 'LOCAL'
THEN 'EXTENT MANAGEMENT LOCAL '||
      CASE WHEN ts.allocation_type = 'SYSTEM'
           THEN 'AUTOALLOCATE;'
           WHEN ts.allocation_type = 'UNIFORM'
           THEN 'UNIFORM SIZE '||
           to_char(ts.initial_extent/1024)||'K;'
      END
Storage Clause/Extent
Managment
OEM_REPOSITORY   EXTENT MANAGEMENT LOCAL AUTOALLOCATE;
TEMP             EXTENT MANAGEMENT LOCAL UNIFORM SIZE 10240K;
TEMP2            DEFAULT STORAGE ( INITIAL 40K
                                   NEXT 40K
                                   MINEXTENTS 1
                                   PCTINCREASE 50);
TOOLS            DEFAULT STORAGE ( INITIAL 32K
                                   NEXT 32K
                                   MINEXTENTS 1
                                   MAXEXTENTS 4096
                                   PCTINCREASE 0);
Spooling Output
♦ SPOOL <filename>
♦ SPOOL OFF
♦ SPOOL command will overwrite the file if
 is exists…and not even ask you “Are You
 Sure?”
  – be careful not to SPOOL
    <sql_filename>…you’ll lose your work
Complete Script
♦ Complete script is attached at the end
♦ Has been tested in 8.1.7 and 9.0.1 on
  Win2K
♦ Still room for improvement and missing
  clauses…
  – Same script was very simple in 7.3!
Notes & Addendum
♦ Formatting not always exact
   – Especially Line Spacing
♦ Verify all scripts with new versions and
  features
  – Data Dictionary structure and data can change
    between releases

More Related Content

What's hot

Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain ExplainedJeremy Coates
 
Oracle naveen Sql
Oracle naveen   SqlOracle naveen   Sql
Oracle naveen Sqlnaveen
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Vidyasagar Mundroy
 
STRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGESTRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGESarithaDhanapal
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptgourav kottawar
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql newSANTOSH RATH
 
Avinash database
Avinash databaseAvinash database
Avinash databaseavibmas
 
Mysqlppt
MysqlpptMysqlppt
MysqlpptReka
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive TechandMate
 
Java class 8
Java class 8Java class 8
Java class 8Edureka!
 

What's hot (17)

Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
Lab2 ddl commands
Lab2 ddl commandsLab2 ddl commands
Lab2 ddl commands
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
My sql.ppt
My sql.pptMy sql.ppt
My sql.ppt
 
Oracle naveen Sql
Oracle naveen   SqlOracle naveen   Sql
Oracle naveen Sql
 
Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)Database Systems - SQL - DDL Statements (Chapter 3/2)
Database Systems - SQL - DDL Statements (Chapter 3/2)
 
Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 
STRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGESTRUCTURED QUERY LANGUAGE
STRUCTURED QUERY LANGUAGE
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Avinash database
Avinash databaseAvinash database
Avinash database
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Java class 8
Java class 8Java class 8
Java class 8
 

Viewers also liked

Syllabus ref01
Syllabus ref01Syllabus ref01
Syllabus ref01SongTu
 
Software Testing in a Distributed Environment
Software Testing in a Distributed EnvironmentSoftware Testing in a Distributed Environment
Software Testing in a Distributed EnvironmentPerforce
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseDBrow Adm
 
My Edited Environmental Scanning Power point presentation
My Edited Environmental Scanning Power point presentationMy Edited Environmental Scanning Power point presentation
My Edited Environmental Scanning Power point presentationSamantha Isabel
 
Indice Arq En Madera U3
Indice Arq En  Madera U3Indice Arq En  Madera U3
Indice Arq En Madera U3lorena_k
 
Ms sql developer
Ms sql developerMs sql developer
Ms sql developerTripti Jha
 
How to build a proper software staging environment for testing
How to build a proper software staging environment for testing How to build a proper software staging environment for testing
How to build a proper software staging environment for testing TestCampRO
 
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...vlearnqtp
 
My Experience Using Oracle SQL Plan Baselines 11g/12c
My Experience Using Oracle SQL Plan Baselines 11g/12cMy Experience Using Oracle SQL Plan Baselines 11g/12c
My Experience Using Oracle SQL Plan Baselines 11g/12cNelson Calero
 
02 software test plan template
02 software test plan template02 software test plan template
02 software test plan templateAndrei Hortúa
 
Fresher interview question for software testing (QA) manual + basic automation
Fresher interview question for software testing (QA) manual + basic automationFresher interview question for software testing (QA) manual + basic automation
Fresher interview question for software testing (QA) manual + basic automationRakesh Hansalia
 
SOAP-UI The Web service Testing
SOAP-UI The Web service TestingSOAP-UI The Web service Testing
SOAP-UI The Web service TestingGanesh Mandala
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUITesting World
 
3 tier architecture
3 tier architecture3 tier architecture
3 tier architecturetahir khan
 
Case study on Banking Software Testing - FINACLE : UAT
Case study on Banking Software Testing - FINACLE : UATCase study on Banking Software Testing - FINACLE : UAT
Case study on Banking Software Testing - FINACLE : UATOAK Systems Pvt Ltd
 

Viewers also liked (20)

Syllabus ref01
Syllabus ref01Syllabus ref01
Syllabus ref01
 
Software Testing in a Distributed Environment
Software Testing in a Distributed EnvironmentSoftware Testing in a Distributed Environment
Software Testing in a Distributed Environment
 
Tutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online DatabaseTutorial - Learn SQL with Live Online Database
Tutorial - Learn SQL with Live Online Database
 
My Edited Environmental Scanning Power point presentation
My Edited Environmental Scanning Power point presentationMy Edited Environmental Scanning Power point presentation
My Edited Environmental Scanning Power point presentation
 
Indice Arq En Madera U3
Indice Arq En  Madera U3Indice Arq En  Madera U3
Indice Arq En Madera U3
 
Ms sql developer
Ms sql developerMs sql developer
Ms sql developer
 
How to build a proper software staging environment for testing
How to build a proper software staging environment for testing How to build a proper software staging environment for testing
How to build a proper software staging environment for testing
 
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...
HP ALM, HP QC 11,QC 11, Quality Center 11, SAP TAO, SAP TAO 3.0, SAP TAO 4.0,...
 
Learn SQL Quickly
Learn SQL QuicklyLearn SQL Quickly
Learn SQL Quickly
 
My Experience Using Oracle SQL Plan Baselines 11g/12c
My Experience Using Oracle SQL Plan Baselines 11g/12cMy Experience Using Oracle SQL Plan Baselines 11g/12c
My Experience Using Oracle SQL Plan Baselines 11g/12c
 
3 tier architecture
3 tier architecture3 tier architecture
3 tier architecture
 
02 software test plan template
02 software test plan template02 software test plan template
02 software test plan template
 
Fresher interview question for software testing (QA) manual + basic automation
Fresher interview question for software testing (QA) manual + basic automationFresher interview question for software testing (QA) manual + basic automation
Fresher interview question for software testing (QA) manual + basic automation
 
Sap mm
Sap mmSap mm
Sap mm
 
SOAP-UI The Web service Testing
SOAP-UI The Web service TestingSOAP-UI The Web service Testing
SOAP-UI The Web service Testing
 
Learn SoapUI
Learn SoapUILearn SoapUI
Learn SoapUI
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUI
 
11 software testing_strategy
11 software testing_strategy11 software testing_strategy
11 software testing_strategy
 
3 tier architecture
3 tier architecture3 tier architecture
3 tier architecture
 
Case study on Banking Software Testing - FINACLE : UAT
Case study on Banking Software Testing - FINACLE : UATCase study on Banking Software Testing - FINACLE : UAT
Case study on Banking Software Testing - FINACLE : UAT
 

Similar to Sql for dbaspresentation

MYSQL
MYSQLMYSQL
MYSQLARJUN
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standardsAlessandro Baratella
 
COMPUTERS SQL
COMPUTERS SQL COMPUTERS SQL
COMPUTERS SQL Rc Os
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queriesKnoldus Inc.
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...Alex Zaballa
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 
MySQL notes - Basic Commands and Definitions
MySQL notes - Basic Commands and DefinitionsMySQL notes - Basic Commands and Definitions
MySQL notes - Basic Commands and DefinitionsDeepakDeedarSingla
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql SyntaxReka
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorialamitabros
 
Introduction to Oracle Database.pptx
Introduction to Oracle Database.pptxIntroduction to Oracle Database.pptx
Introduction to Oracle Database.pptxSiddhantBhardwaj26
 

Similar to Sql for dbaspresentation (20)

MYSQL
MYSQLMYSQL
MYSQL
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
COMPUTERS SQL
COMPUTERS SQL COMPUTERS SQL
COMPUTERS SQL
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
lovely
lovelylovely
lovely
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Dbms
DbmsDbms
Dbms
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Basics on SQL queries
Basics on SQL queriesBasics on SQL queries
Basics on SQL queries
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
Dbms &amp; oracle
Dbms &amp; oracleDbms &amp; oracle
Dbms &amp; oracle
 
Hira
HiraHira
Hira
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
MySQL notes - Basic Commands and Definitions
MySQL notes - Basic Commands and DefinitionsMySQL notes - Basic Commands and Definitions
MySQL notes - Basic Commands and Definitions
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Introduction to Oracle Database.pptx
Introduction to Oracle Database.pptxIntroduction to Oracle Database.pptx
Introduction to Oracle Database.pptx
 

More from oracle documents (20)

Applyinga blockcentricapproachtotuning
Applyinga blockcentricapproachtotuningApplyinga blockcentricapproachtotuning
Applyinga blockcentricapproachtotuning
 
Windowsosauthent
WindowsosauthentWindowsosauthent
Windowsosauthent
 
Whatistnsnames
WhatistnsnamesWhatistnsnames
Whatistnsnames
 
Whatisadatabaselink
WhatisadatabaselinkWhatisadatabaselink
Whatisadatabaselink
 
Varraysandnestedtables
VarraysandnestedtablesVarraysandnestedtables
Varraysandnestedtables
 
Usertracing
UsertracingUsertracing
Usertracing
 
Userpasswrd
UserpasswrdUserpasswrd
Userpasswrd
 
Userlimit
UserlimitUserlimit
Userlimit
 
Undo internalspresentation
Undo internalspresentationUndo internalspresentation
Undo internalspresentation
 
Undo internals paper
Undo internals paperUndo internals paper
Undo internals paper
 
Tablespacelmt
TablespacelmtTablespacelmt
Tablespacelmt
 
Tablerename
TablerenameTablerename
Tablerename
 
Sql scripting sorcerypresentation
Sql scripting sorcerypresentationSql scripting sorcerypresentation
Sql scripting sorcerypresentation
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
 
Sequencereset
SequenceresetSequencereset
Sequencereset
 
Rollbacksizes
RollbacksizesRollbacksizes
Rollbacksizes
 
Rollbackshrinks
RollbackshrinksRollbackshrinks
Rollbackshrinks
 
Rollbacklmt
RollbacklmtRollbacklmt
Rollbacklmt
 
Rollbackblocking
RollbackblockingRollbackblocking
Rollbackblocking
 
Rollback1555s
Rollback1555sRollback1555s
Rollback1555s
 

Sql for dbaspresentation

  • 1. SQL For DBAs Developers and Users will learn something as well! Daniel W. Fink
  • 2. Overview ♦ Where is the information – Data Dictionary views & tables ♦ How can I extract it? – SQL, functions ♦ How can I use it? – SQL*Plus to build and execute the script
  • 3. Method ♦ Build a script that generates the ‘create tablespace’ commands for the database ♦ Not all options considered – AUTOEXTEND – MINEXTENT – ONLINE/OFFLINE – *I have to leave something for you to add… ♦ Not all tablespaces – Enough to demonstrate likely permutations
  • 4. Command ♦ Rules – Tablespace can be TEMPORARY – TEMPORARY tablespace can use DATA files or TEMP files – A single tablespace can have multiple data files ♦ Command structure CREATE [TEMPORARY] TABLESPACE tablespacename [TEMPORARY] {DATAFILE|TEMPFILE} filename filesize EXTENT MANAGEMENT [DICTIONARY|LOCAL [{AUTOALLOCATE|UNIFORM} [size {K|M}]]}]
  • 5. Oracle’s Data Dictionary ♦ Access via Views – 1390 in 8i – 1820 in 9i ♦ DBA_ - Everything in database ♦ ALL_ - What you can see ♦ USER_ What you own ♦ Other – Miscellaneous views
  • 6. Where does it come from? ♦ Views of underlying base objects ♦ Provides level of abstraction – Easy to understand – Hides translations and calculations – READ ONLY!
  • 7. Columns View Text TABLESPACE_NAME select ts.name, INITIAL_EXTENT ts.blocksize * ts.dflinit, NEXT_EXTENT decode(bitand(ts.flags, 3), 1, to_number(NULL), ts.blocksize*ts.dflincr), MIN_EXTENTS ts.dflminext, MAX_EXTENTS decode(ts.contents$, 1, to_number(NULL), ts.dflmaxext), PCT_INCREASE decode(bitand(ts.flags, 3), 1, to_number(NULL), ts.dflextpct), MIN_EXTLEN ts.blocksize * ts.dflminlen, STATUS decode(ts.online$,1,'ONLINE',2,'OFFLINE', 4,'READ ONLY','UNDEFINED'), CONTENTS decode(ts.contents$, 0, 'PERMANENT', 1, 'TEMPORARY'), LOGGING decode(ts.dflogging, 0, 'NOLOGGING', 1, 'LOGGING'), EXTENT_MANAGEMENT decode(ts.bitmapped, 0, 'DICTIONARY', 'LOCAL'), ALLOCATION_TYPE decode(bitand(ts.flags,3),0,'USER',1,'SYSTEM',2,'UNIFORM', 'UNDEFINED'), PLUGGED_IN decode(ts.plugged, 0, 'NO', 'YES') from sys.ts$ ts where ts.online$ != 3
  • 8. Where can I find more information? ♦ Oracle Documentation – Server Reference Guide ♦ DBA_VIEWS – text contains the actual text of the view – SET LONG 10000 in order to see all the text ♦ catalog.sql ♦ sql.bsq
  • 9. Notes on Data Dictionary ♦ ID – COLUMN_ID starts at 1 – EXTENT_ID starts at 0 ♦ Not All DBA_* views have ALL_* and/or USER_* counterparts ♦ DBA_EXTENTS and USER_EXTENTS have different information – USER_EXTENTS does not contain file information ♦ DBA_TAB_COLUMNS – Not just table columns, also views, clusters ♦ DBA_IND_COLUMNS – Reverse Key Indexes have function name instead of table column name for leading column
  • 10. Quick Tour of the Data Dictionary Tables/Views Indexes Storage DBA_TABLES DBA_INDEXES DBA_TABLESPACES DBA_TAB_COLUMNS DBA_IND_COLUMNS DBA_DATA_FILES DBA_TAB_COL_STATISTICS DBA_IND_PARTITIONS DBA_TEMP_FILES DBA_TAB_HISTOGRAMS DBA_IND_SUBPARTITIONS DBA_SEGMENTS DBA_PART_TABLES DBA_PART_INDEXES DBA_EXTENTS DBA_TAB_PARTITIONS DBA_ROLLBACK_SEGS DBA_TAB_SUBPARTITIONS Users DBA_FREE_SPACE DBA_CONSTRAINTS DBA_USERS DBA_CONS_COLUMNS DBA_ROLES DBA_VIEWS DBA_ROLE_PRIVS DBA_TAB_PRIVS DBA_SYS_PRIVS DBA_PROFILES
  • 11. Data Dictionary views for script ♦ DBA_TABLESPACES – All tablespaces in database ♦ DBA_DATAFILES – All DATAFILEs for all tablespaces ♦ DBA_TEMPFILES – *New in Oracle 8i – Identifies TEMPFILES created by command “create temporary tablespace”
  • 12. Using SQL to Write SQL ♦ Joins ♦ Unions ♦ Functions ♦ Sorting
  • 13. Joins ♦ A relationship using common data (natural or derived) must exist ♦ Inner – If a related row exists, return both main and related row – If a related row does not exist, do not return the main row ♦ Outer – If a related row exists, return both main and related row – If a related row does not exist, return main row and null values for related row
  • 14. Join select t.tablespace_name, d.file_name from dba_tablespaces t, dba_data_files d where d.tablespace_name = t.tablespace_name; TABLESPACE_NAME FILE_NAME --------------- --------------------------------- SYSTEM C:ORADATAORA817SYSTEM01.DBF TOOLS C:ORADATAORA817TOOLS01.DBF TOOLS C:ORADATAORA817TOOLS02.DBF TEMP2 C:ORADATAORA817TEMP201.DBF
  • 15. Union ♦ Set Operation ♦ Used to combine sets of data – Joins & Relationships are not used ♦ Columns must be same number and datatype – A literal expression can be used ♦ Returns one row for each distinct set of values – UNION ALL will return duplicates select statement1 union select statement2
  • 16. File List ♦ File names are listed in – DBA_DATA_FILES (10 rows) – DBA_TEMP_FILES (1 row) ♦ Common Data? – Both contain tablespace_name…
  • 17. File List select d.file_name, t.file_name from dba_data_files d, dba_temp_files t where d.tablespace_name = t.tablespace_name; no rows selected ♦ Why? – Tablespaces use either data files or temp files…not both – Even an outer join will miss rows
  • 18. File List FILE_NAME select file_name ------------------------------ from dba_data_files C:ORADATAORA817RBS01.DBF C:ORADATAORA817SYSTEM01.DBF union C:ORADATAORA817TEMP01.DBF C:ORADATAORA817TEMP201.DBF select file_name C:ORADATAORA817TOOLS01.DBF from dba_temp_files; C:ORADATAORA817TOOLS02.DBF
  • 19. Tablespace/File List select tablespace_name TABLESPACE_NAME ------------------------------------ from dba_tablespaces C:ORADATAORA817SYSTEM01.DBF union C:ORADATAORA817TEMP01.DBF C:ORADATAORA817TEMP201.DBF select file_name C:ORADATAORA817TOOLS01.DBF from dba_data_files C:ORADATAORA817TOOLS02.DBF SYSTEM union TEMP select file_name TEMP2 from dba_temp_files; TOOLS
  • 20. Functions ♦ Concatenation – Combine 2 or more strings together ♦ DECODE/CASE – Conditional display/decision-making ♦ TO_CHAR – Converts a number or date to a character string ♦ CHR – Displays the ASCII character ♦ ASCII – Displays the ASCII number
  • 21. Concatenation ♦ Combine two or more strings together – Remember to add blanks ♦ CREATE TABLESPACE <ts_name> CONCAT(‘CREATE TABLESPACE ’, tablespace_name) ‘CREATE TABLESPACE ’||tablespace_name
  • 22. DECODE/CASE ♦ Rudimentary decision making function ♦ DECODE available in 7/8/9 ♦ CASE available from 8.1.6+ ♦ Use to determine – Type of tablespace – Extent Management – Datafile separation
  • 23. DECODE ♦ DECODE(expression, comparison1, return1, comparison2, return2, … default) ♦ Can only use equality comparison
  • 24. DECODE If DBA_TABLESPACES.CONTENTS = ‘TEMPORARY’ display ‘TEMPORARY’ ELSE IF DBA_TABLESPACES.CONTENTS = ‘PERMANENT’ display NULL ELSE display NULL select ‘CREATE ‘||decode(contents, ‘TEMPORARY’,‘TEMPORARY ’, ‘PERMANENT’,NULL,NULL)|| ‘TABLESPACE ‘||tablespace_name from dba_tablespaces; CREATE TABLESPACE SYSTEM CREATE TEMPORARY TABLESPACE TEMP CREATE TEMPORARY TABLESPACE TEMP2 CREATE TABLESPACE TOOLS
  • 25. CASE ♦ Introduced in 8.1.6 ♦ Able to return based on variable conditions CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 … ELSE default
  • 26. CASE select ‘CREATE ‘|| CASE WHEN contents=‘TEMPORARY’ THEN ‘TEMPORARY ’ WHEN contents=‘PERMANENT’ THEN NULL ELSE NULL END||’TABLESPACE ‘||tablespace_name from dba_tablespaces; CREATE TABLESPACE SYSTEM CREATE TEMPORARY TABLESPACE TEMP CREATE TEMPORARY TABLESPACE TEMP2 CREATE TABLESPACE TOOLS ♦ Permanent = NULL not currently needed, but included for example
  • 27. Character String Conversion ♦ TO_CHAR([date|number]{,format string}) – Converts numbers or dates to character string – Uses format codes to change display ♦ TO_CHAR(number) – Does not require format string – Oracle will also convert numeric string to number – If you are not formatting, Oracle will automatically convert to string…UNLESS it is used in a UNION
  • 28. Character String Conversion select 12345||’ is a number’ from dual; 12334 is a number select ‘12345’-10 from dual; 12335 select 12345 from dual union select ‘is a number’ from dual; ORA-01790: expression must have same datatype as corresponding expression
  • 29. CHR ♦ CHR is used to ‘print’ special characters – CHR(<ascii_number>) ♦ ASCII can be used to determine the number of the character – ASCII(‘<character>’)
  • 30. Single Tic ♦ Data files in statement must be enclosed in single tic (‘) – ‘ is a character and can be enclosed in ‘ as a character string – but I can never remember how many I need (I think it’s 4…or is it 3…What if I am using it to end a string?) ♦ CHR(39) prints a single ‘
  • 31. Single Tic SQL> select chr(39)||file_name||chr(39) 2 from dba_data_files; 'C:ORADATAORA817SYSTEM01.DBF' 'C:ORADATAORA817TOOLS01.DBF' SQL> select ’’’’||file_name||’’’’ 2 from dba_data_files; 'C:ORADATAORA817SYSTEM01.DBF' 'C:ORADATAORA817TOOLS01.DBF'
  • 32. New Line ♦ CHR(10) ‘prints’ a newline character – Able to output single row of data on multiple lines select ‘Line 1’||chr(10)||’Line 2’ from dual; Line 1 Line 2
  • 33. CREATE TABLESPACE select ‘CREATE TABLESPACE ‘|| t.tablespace_name||chr(10)|| ‘DATAFILE ‘||chr(39)|| d.file_name||chr(39) from dba_tablespaces t, dba_data_files d where d.tablespace_name = t.tablespace_name;
  • 34. CREATE TABLESPACE Error CREATE TABLESPACE SYSTEM DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS02.DBF' CREATE TABLESPACE TEMP2 DATAFILE 'C:ORADATAORA817TEMP201.DBF‘ ♦ 2nd ‘CREATE TABLESPACE TOOLS’ statement will fail… how do we work around?
  • 35. UNION ♦ UNION of DBA_TABLESPACES, DBA_DATA_FILES, DBA_TEMP_FILES ♦ Each SQL statement is executed independently, then the results are combined ♦ Output will be sorted, in column order ♦ ORDER BY must be last line
  • 36. UNION select 'CREATE '||decode(contents, 'TEMPORARY', 'TEMPORARY ', NULL)|| ’TABLESPACE ‘||tablespace_name from dba_tablespaces union select 'DATAFILE '||chr(39)||file_name||chr(39)||' SIZE '||to_char(bytes/1024)||'K' from dba_data_files union select 'TEMPFILE '||chr(39)||file_name||chr(39)||' SIZE '||to_char(bytes/1024)||'K' from dba_temp_files; CREATE TABLESPACE SYSTEM CREATE TEMPORARY TABLESPACE TEMP CREATE TEMPORARY TABLESPACE TEMP2 CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K
  • 37. Errata ♦ Tablespace to File relationship correct, but not in proper order for SQL statement – Proper order of lines in command is missing – We will use columns to sort…but suppress the printing ♦ Still missing storage/extent management clauses… – Later addition…don’t want to clutter up the statements just yet ♦ Statement contains an error
  • 38. SQL*Plus Commands ♦ COLUMN – noprint ♦ SET – sqlprompt – pagesize – feedback
  • 39. COLUMN ♦ The CREATE TABLESPACE line needs to be associated with DATAFILE line ♦ COLUMN command can be used to suppress printing – COLUMN column_name NOPRINT – Size of column will be factored in to LINESIZE
  • 40. COLUMN select tablespace_name ts_name,'CREATE '|| decode(contents, 'TEMPORARY', 'TEMPORARY ', NULL)||’TABLESPACE ‘||tablespace_name sql_command from dba_tablespaces union select tablespace_name ts_name, 'DATAFILE '||chr(39)|| file_name||chr(39)||' SIZE '|| to_char(bytes/1024)||'K' sql_command from dba_data_files union select tablespace_name ts_name,'TEMPFILE '||chr(39)||file_name ||chr(39)||' SIZE '||to_char(bytes/1024)||'K' sql_command from dba_temp_files;
  • 41. COLUMN TS_NAME SQL_COMMAND ------- ------------------------------------------------------- SYSTEM CREATE TABLESPACE SYSTEM SYSTEM DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K TEMP CREATE TEMPORARY TABLESPACE TEMP TEMP TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K TEMP2 CREATE TEMPORARY TABLESPACE TEMP2 TEMP2 DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K TOOLS CREATE TABLESPACE TOOLS TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K TOOLS DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 42. COLUMN Formatting SQL> COLUMN ts_name NOPRINT SQL> / SQL_COMMAND ------------------------------------------------------- CREATE TABLESPACE SYSTEM DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K CREATE TEMPORARY TABLESPACE TEMP TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K CREATE TEMPORARY TABLESPACE TEMP2 DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 43. Formatting Output ♦ Supress all non-sql statement strings ♦ SET – PAGESIZE 0 – suppress all breaks, headings, etc. – FEEDBACK OFF – suppress ’10 Rows Returned’ message – SQLPROMPT “” – removes SQL> prompt • Be careful…it may look like the command hangs
  • 44. Formatting Output SQL> col ts_name noprint SQL> set pagesize 0 feedback off sqlprompt "" / CREATE TABLESPACE SYSTEM DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K CREATE TEMPORARY TABLESPACE TEMP TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K CREATE TEMPORARY TABLESPACE TEMP2 DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 45. OOPS ♦ DBA_TABLESPACES.CONTENTS lists contents, but not type of file… – Each command creates a TEMPORARY tablespace, but the file specs are not the same! CREATE TABLESPACE TEMPORARY <name> TEMPFILE <name> <specs> CREATE TABLESPACE <name> TEMPORARY DATAFILE <name> <specs> ♦ Multiple data or temp files must be separated by a comma
  • 46. Proper Syntax for TEMPORARY select tablespace_name ts_name, 'CREATE TABLESPACE '||tablespace_name|| decode(contents,'TEMPORARY',' TEMPORARY',NULL) sql_command from dba_tablespaces where tablespace_name in (select tablespace_name from dba_data_files) union select tablespace_name ts_name, 'CREATE '||decode(contents,'TEMPORARY','TEMPORARY ',NULL)|| ’TABLESPACE ‘|| tablespace_name sql_command from dba_tablespaces where tablespace_name in (select tablespace_name from dba_temp_files) union select tablespace_name ts_name, 'DATAFILE '||chr(39)||file_name||chr(39)||' SIZE '|| to_char(bytes/1024)||'K' sql_command from dba_data_files union select tablespace_name ts_name, 'TEMPFILE '||chr(39)||file_name||chr(39)||' SIZE '|| to_char(bytes/1024)||'K' sql_command from dba_temp_files
  • 47. Proper Syntax for TEMPORARY CREATE TABLESPACE SYSTEM DATAFILE 'C:ORADATAORA817SYSTEM01.DBF' SIZE 280576K CREATE TEMPORARY TABLESPACE TEMP TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K CREATE TABLESPACE TEMP2 TEMPORARY DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K DATAFILE 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 48. Proper Syntax for Multiple Files CREATE TABLESPACE <tsname> DATAFILE <filename> <filespecs>, <filename> <filespecs> ♦ Where can the comma go? – After the file specs OR – Before the next file name • Logic easier for 2nd choice ♦ File order is not important – Each file has a numeric ID – Skip the file with the lowest ID
  • 49. Proper Syntax for Multiple Files ♦ Add file_id as a column and sort by it ♦ While we are at it…add sql_sort column to insure proper order of statements ♦ Current Sort Order – tablespace_name – ts_sort (each part of union has a new value) – sql_sort (file_id or derived value)
  • 50. Proper Syntax for Multiple Files select tablespace_name ts_name, 0 ts_sort, 0 sql_sort, <create tablespace line> union select tablespace_name ts_name, 1 ts_sort, file_id sql_sort <datafile line> union select tablespace_name ts_name, 1 ts_sort, file_id sql_sort <tempfile line> union select tablespace_name ts_name, 2 ts_sort, 0 sql_sort <storage line> order by ts_name, ts_sort, sql_sort;
  • 51. Multiple Files select df.tablespace_name ts_name, 1 ts_sort, file_id sql_sort, decode(df.file_id,tfi.min_file_id,'DATAFILE ', ', ')||chr(39)||df.file_name||chr(39)|| ' SIZE '||to_char(df.bytes/1024)||'K' sql_command from dba_data_files df, (select tablespace_name t_name, min(file_id) min_file_id from dba_data_files group by tablespace_name) tfi where df.tablespace_name = tfi.t_name and tablespace_name != 'SYSTEM' ♦ Because we are sorting on file_id, we know that the ‘first’ file will be the first displayed
  • 52. Proper Output (with columns) TS_NAME TS SQL SQL_COMMAND ------- ---- ----- ------------------------------------------------------------ TEMP 0 0 CREATE TEMPORARY TABLESPACE TEMP TEMP 1 1 TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K TEMP2 0 0 CREATE TABLESPACE TEMP2 TEMPORARY TEMP2 1 4 DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K TOOLS 0 0 CREATE TABLESPACE TOOLS TOOLS 1 5 DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K TOOLS 1 10 , 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 53. Proper Output (without columns) CREATE TEMPORARY TABLESPACE TEMP TEMPFILE 'C:ORADATAORA817TEMP01.DBF' SIZE 204800K CREATE TABLESPACE TEMP2 TEMPORARY DATAFILE 'C:ORADATAORA817TEMP201.DBF' SIZE 102400K CREATE TABLESPACE TOOLS DATAFILE 'C:ORADATAORA817TOOLS01.DBF' SIZE 12288K , 'C:ORADATAORA817TOOLS02.DBF' SIZE 102400K
  • 54. What’s Next? ♦ Extent Management & Storage Clause – Dictionary Extent Management is default, no need to specify – DEFAULT STORAGE and LOCAL extent management are mutually exclusive ♦ Interesting notes… – Not all Tablespaces have NEXT defined – Not all Tablespaces have MAXEXTENTS defined – What else may be NULL?
  • 55. Extent Management & Storage ♦ Extent Management can be – LOCAL • AUTOALLOCATE • UNIFORM SIZE – DICTIONARY • default…no need to specify
  • 56. Dictionary Extent Management CASE WHEN ts.extent_management = 'DICTIONARY' THEN 'DEFAULT STORAGE ('|| decode(ts.initial_extent, NULL, NULL, ' INITIAL '||to_char(ts.initial_extent/1024)||'K')|| decode(ts.next_extent, NULL, NULL, ' NEXT'||to_char(ts.next_extent/1024)||'K')|| decode(ts.min_extents, NULL, NULL, ' MINEXTENTS '||to_char(ts.min_extents))|| decode(ts.max_extents, NULL, NULL, ' MAXEXTENTS '||to_char(ts.max_extents))|| decode(ts.pct_increase, NULL, NULL, ' PCTINCREASE'||to_char(ts.pct_increase))||');‘
  • 57. Local Extent Management ♦ Allocation type and the command are not the same! WHEN ts.extent_management = 'LOCAL' THEN 'EXTENT MANAGEMENT LOCAL '|| CASE WHEN ts.allocation_type = 'SYSTEM' THEN 'AUTOALLOCATE;' WHEN ts.allocation_type = 'UNIFORM' THEN 'UNIFORM SIZE '|| to_char(ts.initial_extent/1024)||'K;' END
  • 58. Storage Clause/Extent Managment OEM_REPOSITORY EXTENT MANAGEMENT LOCAL AUTOALLOCATE; TEMP EXTENT MANAGEMENT LOCAL UNIFORM SIZE 10240K; TEMP2 DEFAULT STORAGE ( INITIAL 40K NEXT 40K MINEXTENTS 1 PCTINCREASE 50); TOOLS DEFAULT STORAGE ( INITIAL 32K NEXT 32K MINEXTENTS 1 MAXEXTENTS 4096 PCTINCREASE 0);
  • 59. Spooling Output ♦ SPOOL <filename> ♦ SPOOL OFF ♦ SPOOL command will overwrite the file if is exists…and not even ask you “Are You Sure?” – be careful not to SPOOL <sql_filename>…you’ll lose your work
  • 60. Complete Script ♦ Complete script is attached at the end ♦ Has been tested in 8.1.7 and 9.0.1 on Win2K ♦ Still room for improvement and missing clauses… – Same script was very simple in 7.3!
  • 61. Notes & Addendum ♦ Formatting not always exact – Especially Line Spacing ♦ Verify all scripts with new versions and features – Data Dictionary structure and data can change between releases