Category Archives: SQL

Finding SCN for Oracle Database by Date and time

Oracle provides the function TIMESTAMP_TO_SCN to determine the database SCN number for a given time. This is very useful in performing multiple Oracle Administrative tasks. This procedure explains the use of this function to extract SCN.

1. Logon to Oracle Database server as the Oracle software owner and start SQLPLUS.

[root@linux2 etc]# su – oracle
Last login: Thu Jun 1 09:25:23 EST 2017 on pts/1
[oracle@linux2 ~]$
[oracle@linux2 ~]$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.2.0 Production on Thu Jun 1 13:47:01 2017

Copyright (c) 1982, 2014, Oracle. All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL>

2. Determine Oracle SCN one hour ago by specifying sysdate-1/24

SQL> select timestamp_to_scn(sysdate-1/24) from dual;

TIMESTAMP_TO_SCN(SYSDATE-1/24)
——————————
5062307

SQL>

3. Determine Oracle SCN 1 day ago by specifying sysdate-1

SQL> select timestamp_to_scn(sysdate-1) from dual;

TIMESTAMP_TO_SCN(SYSDATE-1)
—————————
4975332

SQL>

4. Determine Oracle SCN 1 week ago by specifying sysdate-7

SQL> select timestamp_to_scn(sysdate-7) from dual;

TIMESTAMP_TO_SCN(SYSDATE-7)
—————————
4696226

SQL>

5. Determine Oracle SCN by specific date time by using the to_date() function with appropriate date mask.

SQL> select timestamp_to_scn(to_date(’25-MAY-2017 06:30:00′,’DD-MON-YYYY HH24:MI_SS’)) from dual;

TIMESTAMP_TO_SCN(TO_DATE(’25-MAY-201706:30:00′,’DD-MON-YYYYHH24:MI_SS’))
————————————————————————
4696226

SQL>

6. This completes the use of the function TIMESTAMP_TO_SCN.

Larry Catt
OCP

Oracle 12c – DBMS_SPM – Creating SQL Plan

Oracle 12c provides the DBMS_SPM package for managing plan evolution.   This article demonstrates the creation of SQL Plan using the DBMS_SPM package.

 

 

  1. Logon to you database server as the oracle software owner and connect to SQLPLUS as sysdba.

 

[root@linux2 ~]# su – oracle

Last login: Tue Dec 27 07:53:43 EST 2016 on pts/2

Enter database to use:

1 – ORCL

2 – CDB1

Option >

1

[oracle@linux2 ~]$ sqlplus / as sysdba

 

SQL*Plus: Release 12.1.0.2.0 Production on Wed Dec 28 11:06:31 2016

 

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

 

 

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics, Real Application Testing

and Unified Auditing options

 

SQL>

  1. Create test table for SPM test and populate with values.

 

create table test_spm(val_1 number, val_2 char(1));

 

insert into  test_spm

select level, ‘a’ from dual connect by level <=100;

 

 

SQL> create table test_spm(val_1 number, val_2 char(1));

 

Table created.

 

SQL> insert into  test_spm

  2  select level, ‘a’ from dual connect by level <=100;

 

100 rows created.

 

SQL> commit;

 

Commit complete.

 

  1. Get the SQL PLAN name by setting the AUTOTRACE to TRACE and executing query against test table. SQL PLAN NAME in this example is SQL_PLAN_891rxd509mzp3eb1890ae.

SET AUTOTRACE TRACE

select * from test_spm;

 

SET AUTOTRACE TRACE

select * from test_spm;SQL> SQL>

 

100 rows selected.

 

 

Execution Plan

———————————————————-

Plan hash value: 1145642998

 

——————————————————————————

| Id  | Operation         | Name     | Rows  | Bytes | Cost (%CPU)| Time     |

——————————————————————————

|   0 | SELECT STATEMENT  |          |   100 |   500 |     2   (0)| 00:00:01 |

|   1 |  TABLE ACCESS FULL| TEST_SPM |   100 |   500 |     2   (0)| 00:00:01 |

——————————————————————————

 

Note

—–

   – dynamic statistics used: dynamic sampling (level=AUTO)

   – SQL plan baseline “SQL_PLAN_891rxd509mzp3eb1890ae” used for this statement

 

 

Statistics

———————————————————-

          0  recursive calls

          0  db block gets

         10  consistent gets

          0  physical reads

          0  redo size

       2816  bytes sent via SQL*Net to client

        617  bytes received via SQL*Net from client

          8  SQL*Net roundtrips to/from client

          0  sorts (memory)

          0  sorts (disk)

        100  rows processed

 

SQL>

 

  1. Set autotrace off.

 

set autotrace off;

SQL> set autotrace off;

 

  1. Get the SQL_HANDLE from PLAN_NAME out of the dba_sql_plan_baselines table.

 

SELECT sql_handle, plan_name, enabled, accepted

FROM   dba_sql_plan_baselines

WHERE  plan_name = ‘SQL_PLAN_891rxd509mzp3eb1890ae’;

 

 

SELECT sql_handle, plan_name, enabled, accepted

FROM   dba_sql_plan_baselines

WHERE  plan_name = ‘SQL_PLAN_891rxd509mzp3eb1890ae’;SQL> SQL>   2    3

 

SQL_HANDLE           PLAN_NAME                      ENA ACC

——————– —————————— — —

SQL_8486fd694099fea3 SQL_PLAN_891rxd509mzp3eb1890ae YES YES

 

SQL>

 

  1. Create an evolve task using the function CREATE_EVOLVE_TASK function with SQL_HANDLE from above.

 

SET SERVEROUTPUT ON

DECLARE

  l_return VARCHAR2(32767);

BEGIN

  l_return := DBMS_SPM.create_evolve_task(sql_handle => ‘SQL_8486fd694099fea3’);

  DBMS_OUTPUT.put_line(‘Task Name: ‘ || l_return);

END;

/

SQL> SET SERVEROUTPUT ON

DECLARE

  l_return VARCHAR2(32767);

BEGIN

  l_return := DBMS_SPM.create_evolve_task(sql_handle => ‘SQL_8486fd694099fea3’);

  DBMS_OUTPUT.put_line(‘Task Name: ‘ || l_return);

END;

/SQL>   2    3    4    5    6    7

Task Name: TASK_1049

 

PL/SQL procedure successfully completed.

 

SQL>

 

  1. Execute the evolve task using the DBMS_SPM.execute_evolve_task function and the TASK_NAME from above.

 

SET SERVEROUTPUT ON

DECLARE

  l_return VARCHAR2(32767);

BEGIN

  l_return := DBMS_SPM.execute_evolve_task(task_name => ‘TASK_1049’);

  DBMS_OUTPUT.put_line(‘Execution Name: ‘ || l_return);

END;

/

 

SQL> SET SERVEROUTPUT ON

DECLARE

  l_return VARCHAR2(32767);

BEGIN

  l_return := DBMS_SPM.execute_evolve_task(task_name => ‘TASK_1049’);

  DBMS_OUTPUT.put_line(‘Execution Name: ‘ || l_return);

END;

/SQL>   2    3    4    5    6    7

Execution Name: EXEC_1082

 

PL/SQL procedure successfully completed.

 

SQL>

 

  1. Report on the task outcome using the DBMS_SPM.report_evolve_task function and the TASK_NAME and EXECUTION_NAME from above.

 

SET LONG 1000000 PAGESIZE 1000 LONGCHUNKSIZE 100 LINESIZE 100

 

SELECT DBMS_SPM.report_evolve_task(task_name => ‘TASK_1049’, execution_name => ‘EXEC_1082’) AS output

FROM   dual;

 

SQL>

SET LONG 1000000 PAGESIZE 1000 LONGCHUNKSIZE 100 LINESIZE 100

 

SELECT DBMS_SPM.report_evolve_task(task_name => ‘TASK_1049’, execution_name => ‘EXEC_1082’) AS output

FROM   dual;SQL> SQL> SQL>   2

 

OUTPUT

—————————————————————————————————-

GENERAL INFORMATION SECTION

———————————————————————————————

 

 Task Information:

 ———————————————

 Task Name            : TASK_1049

 Task Owner           : SYS

 Execution Name       : EXEC_1082

 Execution Type       : SPM EVOLVE

 Scope                : COMPREHENSIVE

 Status               : COMPLETED

 Started              : 12/28/2016 15:07:14

 Finished             : 12/28/2016 15:07:14

 Last Updated         : 12/28/2016 15:07:14

 Global Time Limit    : 2147483646

 Per-Plan Time Limit  : UNUSED

 Number of Errors     : 0

———————————————————————————————

 

SUMMARY SECTION

———————————————————————————————

  Number of plans processed  : 0

  Number of findings         : 0

  Number of recommendations  : 0

  Number of errors           : 0

———————————————————————————————

SQL>

 

  1. Implement the recommendations in the task with the DBMS_SPM.implement_evolve_task function and the TASK_NAME from above.

 

SET SERVEROUTPUT ON

DECLARE

  l_return NUMBER;

BEGIN

  l_return := DBMS_SPM.implement_evolve_task(task_name => ‘TASK_1049’);

  DBMS_OUTPUT.put_line(‘Plans Accepted: ‘ || l_return);

END;

/

SQL>

SET SERVEROUTPUT ON

DECLARE

  l_return NUMBER;

BEGIN

  l_return := DBMS_SPM.implement_evolve_task(task_name => ‘TASK_1049’);

  DBMS_OUTPUT.put_line(‘Plans Accepted: ‘ || l_return);

END;

/SQL> SQL>   2    3    4    5    6    7

Plans Accepted: 0

 

PL/SQL procedure successfully completed.

 

SQL>

 

  1. Verify the change by querying the DBA_SQL_PLAN_BASELINES table witht eh SQL_HANDLE from above.

 

SELECT sql_handle, plan_name, enabled, accepted

FROM   dba_sql_plan_baselines

WHERE  sql_handle = ‘SQL_8486fd694099fea3’;

 

 

 

SQL> SELECT sql_handle, plan_name, enabled, accepted

FROM   dba_sql_plan_baselines

WHERE  sql_handle = ‘SQL_8486fd694099fea3’;

  2    3

SQL_HANDLE           PLAN_NAME                      ENA ACC

——————– —————————— — —

SQL_8486fd694099fea3 SQL_PLAN_891rxd509mzp3eb1890ae YES YES

 

SQL>

 

  1. This complets use of DBMS_SPM for creating SQL plan.

 

 

Larry Catt

OCP

Oracle 12c – Use Row limit clause

Oracle 12c now supports top-N SQL queries (those that return limited number of rows after sort operation).    In previous releases this was performed by limiting return by the pseudo column ROWNUM before the ORDER BY clause but was not a true top-N query.   This has been resolved with two new clauses:   FETCH FIRST and OFFSET.

 

 

Examples:

 

FETCH FIRST – the example below use FETCH FIRST to return the 3 highest salaried persons from scott.emp.

 

 

  1. Logon to SQLPLUS as SCOTT.

 

[oracle@linux2 ~]$ sqlplus scott/password

 

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jan 4 07:45:52 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Last Successful login time: Tue Jan 03 2016 12:44:03 -05:00

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics, Real Application Testing

and Unified Auditing options

 

SQL>

 

  1. Execute the query below:

 

select ename, sal from scott.emp order by sal desc

fetch first 3 rows only;

 

SQL> select ename, sal from scott.emp order by sal desc

fetch first 3 rows only;

  2

ENAME             SAL

———- ———-

KING             5000

SCOTT            3000

FORD             3000

 

SQL>

 

 

  1. Use ASC clause to get the reverse order, as below

 

select ename, sal from scott.emp order by sal asc

fetch first 3 rows only;

 

SQL> select ename, sal from scott.emp order by sal asc

fetch first 3 rows only;

  2

ENAME             SAL

———- ———-

SMITH             800

JAMES             950

DOE              1000

 

SQL>

 

  1. FETCH LAST clause does not exist must use ASC FETCH FIRST clause.

 

 

OFFSET – Skips a number of rows in the ordered list and with FETCH NEXT gives a range of rows.

 

  1. Logon to SQLPLUS as SCOTT.

 

[oracle@linux2 ~]$ sqlplus scott/password

 

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jan 4 07:45:52 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Last Successful login time: Tue Jan 03 2016 12:44:03 -05:00

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics, Real Application Testing

and Unified Auditing options

 

SQL>

 

  1. Execute the query below:

 

 

select ename, sal from scott.emp order by sal desc offset 3 rows fetch next 3 rows only;

 

 

SQL> select ename, sal from scott.emp order by sal desc offset 3 rows fetch next 3 rows only;

 

ENAME             SAL

———- ———-

JONES            2975

BLAKE            2850

CLARK            2450

 

SQL>

 

 

 

 

FETCH NEXT can also give a percentage say you want to know the top 10% of all salaries.

 

  1. Logon to SQLPLUS as SCOTT.

 

[oracle@linux2 ~]$ sqlplus scott/password

 

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jan 4 07:45:52 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Last Successful login time: Tue Jan 03 2016 12:44:03 -05:00

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics, Real Application Testing

and Unified Auditing options

 

SQL>

 

  1. Execute the query below:

 

 

select ename, sal from scott.emp order by sal desc fetch next 10 percent rows only;

 

 

SQL> select ename, sal from scott.emp order by sal desc fetch next 10 percent rows only;

 

ENAME             SAL

———- ———-

KING             5000

FORD             3000

 

SQL>

 

 

 

  1. This completes using row limit clauses in Oracle 12c.

 

Larry Catt

OCP

Oracle 12c – Adaptive Execution Plan

In Oracle 12c Adaptive Execution Plans allows optimizer to make Janision on SQL at runtime and in mid execution.  It will actually make sub-plans and collect statistics to make final Janision on execution.   Currently release only supports adaptive execution plans for join and parallel operations.

This article will demonstrate the use of Adaptive Execution Plan against a set test tables.

 

  1. Logon server as the oracle software owner and logon to SQLPLUS as the user scott.

 

[root@linux2 ~]# su – oracle

Last login: Thu Jan 15 13:05:52 EST 2016 on pts/1

Enter database to use:

1 – ORCL

2 – CDB1

Option >

1

[oracle@linux2 schema]$ sqlplus scott/password

 

SQL*Plus: Release 12.1.0.2.0 Production on Fri Jan 23 08:12:04 2016

 

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

 

Last Successful login time: Fri Jan 23 2016 08:10:57 -05:00

 

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics, Real Application Testing

and Unified Auditing options

 

SQL>

 

 

  1. Create the user test with dba privileges.

 

 

SQL> create user test identified by test

default tablespace users quota unlimited on users;  2

 

User created.

 

SQL> grant dba to test;

 

Grant succeeded.

 

  1. Create a test table test_tab1 and 200 insert values.

 

SQL> create table test.test_tab1(

col_a number,

col_b varchar2(10),

constraint tab1_pk primary key(col_a));  2    3    4

 

Table created.

 

SQL> Janlare

  2  val_a number:=1;

  3  val_b varchar2(10):=’a’;

  4

  5  begin

  6

  7  while val_a<200

  8  loop

  9  insert into test.test_tab1(col_a, col_b)

 10  values(val_a, val_b);

 11

 12  val_a:=val_a+1;

 13  if val_b=’z’

 14  then

 15  val_b:=’a’;

 16  else

 17  val_b:=chr(ascii(val_b) + 1);

 18  end if;

 19  end loop;

 20  commit;

 21  end;

 22  /

 

PL/SQL procedure successfully completed.

 

SQL> commit;

 

Commit complete.

 

SQL>

 

  1. Create test table test_tab2 with foreign key back to test_tab1. NOTE:  Adaptive Execution only work with join operations.

 

SQL> create table test.test_tab2(

tab1_col_a number,

col_a number,

col_b varchar2(10),

constraint tab2_tab1_fk foreign key (tab1_col_a) references test.test_tab1(col_a));  2    3    4    5

 

Table created.

 

SQL>

 

 

  1. Populate test table test_tab2.

 

SQL> insert into test.test_tab2(tab1_col_a, col_a, col_b)

select col_a, col_a+1, ‘testing’

from test.test_tab1 where 1=mod(col_a,2);  2    3

 

100 rows created.

 

SQL> commit;

 

Commit complete.

 

SQL>

 

 

  1. Perform an explain for a select join operation on the two tables.

 

SQL> explain plan for select * from test.test_tab2 b, test.test_tab1 a

where a.col_a=tab1_col_a  2

  3  ;

 

Explained.

 

SQL>

 

  1. Now examine the execution plan and not the adaptive remark at the bottom.

 

SQL> select * from table(dbms_xplan.display);

 

PLAN_TABLE_OUTPUT

——————————————————————————————————————————————————————————————————–

Plan hash value: 1368181317

 

——————————————————————————–

| Id  | Operation          | Name      | Rows  | Bytes | Cost (%CPU)| Time     |

——————————————————————————–

|   0 | SELECT STATEMENT   |           |   100 |  5300 |     6   (0)| 00:00:01 |

|*  1 |  HASH JOIN         |           |   100 |  5300 |     6   (0)| 00:00:01 |

|   2 |   TABLE ACCESS FULL| TEST_TAB2 |    82 |  2706 |     3   (0)| 00:00:01 |

|   3 |   TABLE ACCESS FULL| TEST_TAB1 |    82 |  1640 |     3   (0)| 00:00:01 |

——————————————————————————–

 

Predicate Information (identified by operation id):

—————————————————

 

   1 – access(“A”.”COL_A”=”TAB1_COL_A”)

 

Note

—–

   – dynamic statistics used: dynamic sampling (level=AUTO)

   – this is an adaptive plan

 

20 rows selected.

 

SQL>

 

  1. Now use the format => adaptive reference in the dbms_xplan.display function to get the adaptive plan.

 

SQL> SET LINESIZE 200 PAGESIZE 100

SELECT * FROM TABLE(DBMS_XPLAN.display_cursor(format => ‘adaptive’));SQL>

 

PLAN_TABLE_OUTPUT

——————————————————————————————————————————————————————————————————–

SQL_ID  ff5spha9pjuyu, child number 0

————————————-

select * from table(dbms_xplan.display)

 

Plan hash value: 2137789089

 

———————————————————————————————

| Id  | Operation                         | Name    | Rows  | Bytes | Cost (%CPU)| Time     |

———————————————————————————————

|   0 | SELECT STATEMENT                  |         |       |       |    29 (100)|          |

|   1 |  COLLECTION ITERATOR PICKLER FETCH| DISPLAY |  8168 | 16336 |    29   (0)| 00:00:01 |

———————————————————————————————

 

 

13 rows selected.

 

SQL>

 

  1. This completes testing of adaptive execution plan.

 

Larry Catt

OCP

Currently executing SQL in Oracle database

I was just asked by a junior administrator, how to determine what SQL is currently executing against her database. While this may seem a trivial task for those in the industry for some time, I thought it a very good question. The below SQL will display currently executing SQL within an Oracle RDBMS.

1. Logon to SQL*PLUS with dba privileges.

2. Execute the following SQL block against the v$sql and v$session tables. NOTE: in a grid environment, use the gv$ views.

select sql_text from v$sql where sql_id in
(select sql_id from v$session where status=’ACTIVE’);

3. Displayed results show currently executing SQL blocks.

SQL> select sql_text from v$sql where sql_id in
2 (select sql_id from v$session where status=’ACTIVE’);

SQL_TEXT
——————————————————————————–
select sql_text from v$sql where sql_id in (select sql_id from v$session where s
tatus=’ACTIVE’)

Larry Catt, OCP

Oracle – Encoding and Decoding Oracle data with UTL_ENCODE Package

Oracle RDBMS provides the ability to encode and decode data through the package UTL_ENCODE. This functionality can be extremely helpful in the transmission of data over open networks where plan text transmission would not be wanted. In this article we will review the use of encoding plain text and decoding the string produced.

1. Logon to your Oracle database server as the Oracle software owner.

2. Logon to SQLPLUS with SYSDBA privileges.

mylinux:> sqlplus '/ as sysdba'

SQL*Plus: Release 10.2.0.4.0 - Production on Wed Jun 30 20:00:09 2009

Copyright (c) 1982, 2007, Oracle. All Rights Reserved.

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>

3. Execute the following PL/SQL block to produce the encoded text string for: Test encode procedure.

set serveroutput on

declare
v_text varchar2(100):='Test encode procedure';
v_encoded_text varchar2(200);
v_ct number;
begin

v_encoded_text:=utl_encode.text_encode(v_text,'WE8ISO8859P1',
UTL_ENCODE.BASE64);
dbms_output.put_line(v_encoded_text);

end;
/

Output from SQL*PLUS

SQL> declare
2
3 v_text varchar2(100):='Test encode procedure';
4 v_encoded_text varchar2(200);
5 v_ct number;
6
7 begin
8
9 v_encoded_text:=utl_encode.text_encode(v_text,'WE8ISO8859P1',
UTL_ENCODE.BASE64);
10
11 dbms_output.put_line(v_encoded_text);
12
13 end;
14 /
VGVzdCBlbmNvZGUgcHJvY2VkdXJl

PL/SQL procedure successfully completed.

SQL>

4. The PL/SQL block executed generated the encoded version of ‘Test encode procedure’ as VGVzdCBlbmNvZGUgcHJvY2VkdXJl. Now we will decode the string with the text decode function.

set serveroutput on

declare

v_text varchar2(100):='VGVzdCBlbmNvZGUgcHJvY2VkdXJl';
v_encoded_text varchar2(200);
v_ct number;

begin

v_encoded_text:=utl_encode.text_decode(v_text,'WE8ISO8859P1',
UTL_ENCODE.BASE64);

dbms_output.put_line(v_encoded_text);

end;
/

Output from SQL*PLUS:

SQL>
SQL> declare
2
3 v_text varchar2(100):='VGVzdCBlbmNvZGUgcHJvY2VkdXJl';
4 v_encoded_text varchar2(200);
5 v_ct number;
6
7 begin
8
9 v_encoded_text:=utl_encode.text_decode(v_text,'WE8ISO8859P1',
UTL_ENCODE.BASE64);
10
11 dbms_output.put_line(v_encoded_text);
12
13 end;
14 /
Test encode procedure

PL/SQL procedure successfully completed.

SQL>

The decode function displays the original text presented to the encode function.

Larry J. Catt, OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com

Execution of Oracle SQL commands from within UNIX or LINUX shell scripts:

In the management of Oracle RDBMS, we frequently have the need to develop shell scripts to manage our databases. This article demonstrates the use of BASH shell script to connect to an Oracle database and execute PL/SQL and SQL statements from within the Oracle database. The following procedure will work on UNIX and LINUX machines.

1. Logon to your Oracle database server as the Oracle software owner.

2. Use vi to create a new file with the name sql_shell_test.sh

mylinux:> vi sql_shell_test.sh
“sql_shell_test.sh” [New file]

~
~

3. Press the ‘a’ key once (for append operations) and past the following text into your file.

sqlplus ‘/ as sysdba’ <

4. Press the keys : –> w –> q and hit the return key to save and exit vi.

5. Execute the chmod command to change you file status to read_write_execute for owner and group

mylinux:> chmod 770 sql_shell_test.sh
mylinux:>

6. As the Oracle software owner, execute the shell script sql_shell_test.sh with the following command.

mylinux:>./sql_shell_test.sh

7. Perform an ls command and you can see that the script has generated the output file test_shell_script_output.lst.

mylinux:>ls -lrt
-rwxrwxrwx 1 oracle dba 148 May 13 03:30 sql_shell_test.sql
-rw-r–r– 1 oracle dba 1391 May 13 03:32 test_shell_script_output.lst
mylinux:>

8. Perform a cat command to see the output of file test_shell_script_output.lst.

mylinux:>cat test_shell_script_output.lst
SQL> select * from v$instance;

INSTANCE_NUMBER INSTANCE_NAME
————— —————-
HOST_NAME
—————————————————————-
VERSION STARTUP_T STATUS PAR THREAD# ARCHIVE LOG_SWITCH_WAIT
—————– ——— ———— — ———- ——- —————
LOGINS SHU DATABASE_STATUS INSTANCE_ROLE ACTIVE_ST BLO
———- — —————– —————— ——— —
1 orcl
frankie
10.2.0.4.0 13-MAY-10 OPEN NO 1 STOPPED
ALLOWED NO ACTIVE PRIMARY_INSTANCE NORMAL NO

SQL> select name, open_mode from v$database;

NAME OPEN_MODE
——— ———-
ORCL READ WRITE

SQL> spool off
mylinux:>

This concludes the execution of Oracle SQL commands from within UNIX or LINUX shell scripts.

Larry J. Catt, OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com

Oracle – Viewing errors generated when writing a PL/SQL program unit.

When you create a PL/SQL block of code within Oracle in the form of a procedure, function, or package and a compilation error occurs; Oracle will not immediately give you the error details. This article details the procedure to view errors generated by a PL/SQL block within SQL*PLUS.

1. Logon to your Oracle database server as the Oracle software owner.

2. Create a file called create_file.sql with the following SQL.

create or replace procedure test_file
is

v_record varchar2(50) := ‘Testing file creation’;
v_file varchar2(30) := ‘test_file.txt’;
v_dir varchar2(512) := ‘/home/lcatt’;
v_write utl_file.file_type;
begin

v_write:=utl_file.fopen(v_dir, v_file, ‘w’, 2000);

utl_file.put_line(v_write, v_record);

utl_file.fclose(v_write);

end test_file;
/

3. Logon to SQLPLUS with SYSDBA privileges.

mylinux:> sqlplus ‘/ as sysdba’

SQL*Plus: Release 10.2.0.4.0 – Production on Thu Apr 22 19:00:09 2010

Copyright (c) 1982, 2007, Oracle. All Rights Reserved.

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 – 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL>

4. Set FEEDBACK and ECHO to on and execute the file create_file.sql.

SQL> set echo on
SQL> set feedback on
SQL> @./create_file.sql
SQL> create or replace procedure test_file
2 is
3
4 v_record varchar2(50) := ‘Testing file creation’;
5 v_file varchar2(30) := ‘test_file.txt’;
6 v_dir varchar2(512) := ‘/home/lcatt’;
7
8 begin
9
10 v_write:=utl_file.fopen(v_dir, v_file, ‘w’, 2000);
11
12 utl_file.put_line(v_write, v_record);
13
14 utl_file.fclose(v_write);
15
16 end test_file;
17 /

Warning: Procedure created with compilation errors.

SQL>

5. The procedure was created with compilation errors, however it does not show you the errors. To see the errors generated in your procedure creation statement, use the SQL*PLUS command: show errors

SQL> show errors
Errors for PROCEDURE TEST_FILE:

LINE/COL ERROR
——– —————————————————————–
10/1 PL/SQL: Statement ignored
10/1 PLS-00201: identifier ‘V_WRITE’ must be declared
12/1 PL/SQL: Statement ignored
12/19 PLS-00201: identifier ‘V_WRITE’ must be declared
14/1 PL/SQL: Statement ignored
14/17 PLS-00201: identifier ‘V_WRITE’ must be declared
SQL>

6. Now you can see that the procedure creation statement is missing the definition for the variable V_WRITE. To correct this error replace the contents of your create_file.sql file with the following text, where the variable v_write is defined as utl_file.file_type.

create or replace procedure test_file
is

v_record varchar2(50) := ‘Testing file creation’;
v_file varchar2(30) := ‘test_file.txt’;
v_dir varchar2(512) := ‘/home/lcatt’;
v_write utl_file.file_type;
begin

v_write:=utl_file.fopen(v_dir, v_file, ‘w’, 2000);

utl_file.put_line(v_write, v_record);

utl_file.fclose(v_write);

end test_file;
/

7. Re-enter SQL*PLUS, set ECHO and FEEDBACK to on, and execute the file create_file.sql.

Mylinux:/home/lcatt:>sqlplus ljcatt

SQL*Plus: Release 10.2.0.4.0 – Production on Thu Apr 22 19:43:17 2010

Copyright (c) 1982, 2007, Oracle. All Rights Reserved.

Enter password:

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 – 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> set feedback on
SQL> set echo on
SQL>@./create_file.sql
SQL> create or replace procedure test_file
2 is
3
4 v_record varchar2(50) := ‘Testing file creation’;
5 v_file varchar2(30) := ‘test_file.txt’;
6 v_dir varchar2(512) := ‘/home/lcatt’;
7 v_write utl_file.file_type;
8 begin
9
10 v_write:=utl_file.fopen(v_dir, v_file, ‘w’, 2000);
11
12 utl_file.put_line(v_write, v_record);
13
14 utl_file.fclose(v_write);
15
16 end test_file;
17 /

Procedure created.

SQL>

The procedure now compiles without error, through the use of the SQL*PLUS command ‘show errors’ which allowed us to see the detailed error message provided by the Oracle RDBMS.

Larry J. Catt, OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com

Senior-Level DBA Interview Question:

With well over a decade of Oracle experience from version 6 to 11g, I have had my share of interviewing prospective DBA employees in a range from Junior to Senior DBAs. Needless to say in this field, technical competence is the key to any new hire and early on I made the blunder of not asking the write questions during the interview. I am sure every senior person or manager has made this mistake and had to deal with either training the person from scratch or letting them go. Either of these options is not desirable in our fast past business world. So, I decided to write a couple of articles which cover what I believe a Junior, Mid, and Senior Oracle DBA should know to fill their prospective positions.

In this article we will cover what a Senior Level DBA should know to be successful. If you have any comments or questions, please email me at larry.catt@relidb.com.

Questions: NOTE: Answers here can be very broad, however they not always wrong. That is why it is important to have a proven DBA on staff or one you can call to review the answers. I have seen very inventive ways to get around the most impossible tasks and while they do not actually meet the standard way of doing the work, I would not count these people out. A person whom thinks outside of the box is very valuable in IT and believe it or not, some of the best DBA’s I have ever met thought completely outside the box, however always accomplished the task.

1. You have a brand new Solaris Machine, freshly built by the SA, with all Oracle RDBMS recommended patching and Kernel Parameters set. Please give the order of tasks to install Oracle up to its latest CPU?

2. You have just moved Oracle Binary files from an ORACLE_HOME on one server to another server. What is the oracle utility command you would use to make this new ORACLE_HOME usable?

3. Tell me why just copying the oracle datafiles from HP-UX to LINUX RHEL and starting the database would not work?

4. In what months does Oracle release CPU patches and what is the utility to apply them.

5. You need to shutdown the oracle database but it will not shutdown with SHUTDOWN IMMEDIATE. How will you shutdown the database?

6. How do you logon to Oracle server without knowing any oracle passwords?

7. How would you determine that SCATTERED READ where occuring?

8. How would you see the SQL of the currently active sessions from a command prompt?

9. When having multiple oracle homes on a single server or client what is the parameter that points all Oracle installs at one TNSNAMES.ORA file.

10. You have ASM database that used by three production systems. The server which the ASM database is shutdown. What happens to the production RDBMS?

Answers:

1. You have a brand new Solaris Machine, freshly built by the SA, with all Oracle RDBMS recommended patching and Kernel Parameters set. Please give the order of tasks to install Oracle up to its latest CPU?

– Verify that all patches are installed and kernel parameters set.(Some not all SA say the system is ready when it is not. You can save yourself a lot of problems by double checking)
– Configuration of .profile or .bash_profile for the Oracle owner.
– Base Installation of Oracle (ie what to get to 10.2.0.4 must install Oracle 10.1 first).
– Upgrade to Oracle Version Desired.
– Upgrade the database(if upgrade is necessary)
– Run UTLRP.SQL.
– Apply lastest CPU patch.
– Run UTLRP.SQL.
– Configuration of Listener.
– Configuration of client TNSNAMES.ORA file.

2. You have just moved Oracle Binary files from an ORACLE_HOME on one server to another server. What is the oracle utility command you would use to make this new ORACLE_HOME usable?

Solution:
Relink all

3. Tell me why just copying the oracle datafiles from HP-UX to LINUX RHEL and starting the database would not work?

Solution:
Differing Indian codes.

4. In what months does Oracle release CPU patches and what is the utility to apply them.

Solution:
JAN, APR, JUL, OCT

5. You need to shutdown the oracle database but it will not shutdown with SHUTDOWN IMMEDIATE. How will you shutdown the database?

Solution:
Kill the smon process.

6. How do you logon to Oracle server without knowing any oracle passwords?

Solution:
Sudo to the Oracle software owners account and logon with the command sqlplus ‘/ as sysdba’

7. How would you determine that SCATTERED READ where?
Solution:

Look in the views v$session_wait or v$session_wait_history.

Could give:

Statspack or EM report.

8. How would you see the SQL of the currently active sessions from a command prompt?

Solution:
Compare tables V$SQL view by sql_address with V$SESSION view of currently active sessions.

9. When having multiple oracle homes on a single server or client what is the parameter that points all Oracle installs at one TNSNAMES.ORA file.

Solution:
TNS_ADMIN

10. You have ASM database that used by three production systems. The server which the ASM database is shutdown. What happens to the production RDBMS?

Solution:
Other database would shutdown abort.

Larry Catt, OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com

Taking an Oracle database out of a multi-Node RAC

I have found during some administrative tasks it is easier to have your system in single NODE configuration. An example of this, would be physical changes the database structure that due not include binary upgrades such as a CPU patch. It is easier to startup, shutdown, and restrict access thorough single stand alone system, rather then a RAC environment with several active nodes. I realize that most of you are quite verse in the user of the SRVCTL utility to administrate the instances and database. However, I would like to show the use of starting up the database in single node from within the database and using SRVCTL just to verify the status.

1. Logon to one node as sysdba.

mylinux1>$ sqlplus ‘/ as sysdba’

SQL*Plus: Release 10.2.0.4.0 – Production on Thu Sep 3 18:47:59 2009

Copyright (c) 1982, 2006, Oracle. All Rights Reserved.

Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 – Production
With the Partitioning, Real Application Clusters, OLAP and Data Mining options

SQL>

2. Execute the following SQL “select inst_id, instance_name, instance_role, host_name from gv$instance;” and as you can see we are attached to a two node RAC.

SQL> select inst_id, instance_name, instance_role, host_name from gv$instance;

INST_ID INSTANCE_NAME INSTANCE_ROLE HOST_NAME
———- ————– —————– ——————
1 node1 PRIMARY_INSTANCE mylinux1
2 node2 PRIMARY_INSTANCE mylinux2

SQL>

3. Exit out of SQL*PLUS and use the SRVCTL utility to obtain the current RAC status. The utility SRVCTL verifies what we saw in the data dictionary view of GV$INSTANCE.

mylinux1>$ srvctl status database -d orcl
Instance node1 is running on node mylinux1
Instance node2 is running on node mylinux2

4. Due to the fact that we have two instance running, we will use the SRVCTL utility to shutdown the database.

mylinux1>$ srvctl stop database -d orcl

5. Again use the SRVCTL utility to view the status of your Instances and the results are displayed that both instance are shutdown.

srvctl status database -d orcl
Instance node1 is not running on node mylinux1
Instance node2 is not running on node mylinux2
mylinux1>$

6. Now you do have a choice here: 1. You could startup the database and a single instance with the SRVCTL utility or 2. You could logon to SQL*PLUS like a non-RAC system and startup the instance and database. We will logon to SQL*PLUS as sysdba and issue the startup command.

mylinux1>$ sqlplus ‘/ as sysdba’

SQL*Plus: Release 10.2.0.4.0 – Production on Thu Sep 3 19:02:13 2009

Copyright (c) 1982, 2006, Oracle. All Rights Reserved.

Connected to an idle instance.

SQL> startup
ORACLE instance started.

Total System Global Area 1795162112 bytes
Fixed Size 1262332 bytes
Variable Size 587205892 bytes
Database Buffers 1191182336 bytes
Redo Buffers 15511552 bytes
Database mounted.
Database opened.
SQL>

7. Execute the following SQL “select inst_id, instance_name, instance_role, host_name from gv$instance;” to display the results of starting the database from NODE1.

SQL> select inst_id, instance_name, instance_role, host_name from gv$instance;

INST_ID INSTANCE_NAME INSTANCE_ROLE HOST_NAME
———- ————– —————– ——————
1 node1 PRIMARY_INSTANCE mylinux1

SQL>

8. You can verify these results with the SRVCTL utility.

mylinux1>$ srvctl status database -d orcl
Instance node1 is running on node mylinux1
Instance node2 is not running on node mylinux2
mylinux1>$

9. Your system is now executing in a SINGLE NODE fashion and you can began your administrative tasks.

Larry Catt OCP 9i, 10g
oracle@allcompute.com
www.allcompute.com