RUNSTATS

•July 25, 2007 • Leave a Comment

HOW TO BUILD RUNSTATS ?

Requisites :

1. ability to user access V$STATNAME, V$MYSTAT, v$TIMER and V$LATCH.

2. grant privileges on user to V_$STATNAME, V_$MYSTAT, V_$TIMER, V_$LATCH that are all owned by SYS.

3. ability to create table, view and package .

Implementation:

1. grant privileges to user

SQL> conn sys/[pswd] as sysdba
Connected.

SQL> grant connect, resource to [user];

Grant succeeded.

SQL> grant create view to [user];

Grant succeeded.

SQL> grant select on v_$statname to [user];

Grant succeeded.

SQL> grant select on v_$mystat to [user];

Grant succeeded.

SQL> grant select on v_$latch to [user];

Grant succeeded.

SQL> grant select on v_$timer to [user];

Grant succeeded.

2. create temporary table ‘run_stats’ and view ’stats’

SQL> conn [user]/[pswd]

Connected.

create global temporary table run_stats
( runid varchar2 (15),
name varchar2 (80),
value int )
on commit preserve rows;

create or replace view stats
as select ‘STAT…’ || a.name name, b.value
from v$statname a, v$mystat b
where a.statistic# = b.statistic#
union all
select ‘LATCH.’ || name, gets
from v$latch
union all
select ‘STAT…Elapsed Time’, hsecs from v$timer;

3. create package of runstats_pkg that includes three process to implement during test steps.

create or replace package runstats_pkg
as
procedure rs_start;
procedure rs_middle;
procedure rs_stop( p_difference_threshold in number default 0 );
end;
/

create or replace package body runstats_pkg
as

g_start number;
g_run1 number;
g_run2 number;

procedure rs_start
is
begin
delete from run_stats;

insert into run_stats
select ‘before’, stats.* from stats;

g_start := dbms_utility.get_time;
end;

procedure rs_middle
is
begin
g_run1 := (dbms_utility.get_time-g_start);

insert into run_stats
select ‘after 1′, stats.* from stats;
g_start := dbms_utility.get_time;

end;

procedure rs_stop(p_difference_threshold in number default 0)
is
begin
g_run2 := (dbms_utility.get_time-g_start);

dbms_output.put_line
( ‘Run1 ran in ‘ || g_run1 || ‘ hsecs’ );
dbms_output.put_line
( ‘Run2 ran in ‘ || g_run2 || ‘ hsecs’ );
dbms_output.put_line
( ‘run 1 ran in ‘ || round(g_run1/g_run2*100,2) ||
‘% of the time’ );
dbms_output.put_line( chr(9) );

insert into run_stats
select ‘after 2′, stats.* from stats;

dbms_output.put_line
( rpad( ‘Name’, 30 ) || lpad( ‘Run1′, 12 ) ||
lpad( ‘Run2′, 12 ) || lpad( ‘Diff’, 12 ) );

for x in
( select rpad( a.name, 30 ) ||
to_char( b.value-a.value, ‘999,999,999′ ) ||
to_char( c.value-b.value, ‘999,999,999′ ) ||
to_char( ( (c.value-b.value)-(b.value-a.value)), ‘999,999,999′ ) data
from run_stats a, run_stats b, run_stats c
where a.name = b.name
and b.name = c.name
and a.runid = ‘before’
and b.runid = ‘after 1′
and c.runid = ‘after 2′
– and (c.value-a.value) > 0
and abs( (c.value-b.value) – (b.value-a.value) )
> p_difference_threshold
order by abs( (c.value-b.value)-(b.value-a.value))
) loop
dbms_output.put_line( x.data );
end loop;

dbms_output.put_line( chr(9) );
dbms_output.put_line
( ‘Run1 latches total versus runs — difference and pct’ );
dbms_output.put_line
( lpad( ‘Run1′, 12 ) || lpad( ‘Run2′, 12 ) ||
lpad( ‘Diff’, 12 ) || lpad( ‘Pct’, 10 ) );

for x in
( select to_char( run1, ‘999,999,999′ ) ||
to_char( run2, ‘999,999,999′ ) ||
to_char( diff, ‘999,999,999′ ) ||
to_char( round( run1/run2*100,2 ), ‘99,999.99′ ) || ‘%’ data
from ( select sum(b.value-a.value) run1, sum(c.value-b.value) run2,
sum( (c.value-b.value)-(b.value-a.value)) diff
from run_stats a, run_stats b, run_stats c
where a.name = b.name
and b.name = c.name
and a.runid = ‘before’
and b.runid = ‘after 1′
and c.runid = ‘after 2′
and a.name like ‘LATCH%’
)
) loop
dbms_output.put_line( x.data );
end loop;
end;

end;
/

Example of runstats:

runstats


Clear buffer cache and shared pool in Oracle

•July 24, 2007 • 1 Comment

Flushing the buffer helps to find out more consistent results for sql traces.

If you want to compare two different cases for performance, flush buffer cache and shared pool before execution of both of them.

It’is a simple alter system command to clear buffer cache and shared pool:

– flush buffer cache to clear recently cached datablocks

SQL > alter system flush buffer_cache;

– flush shared pool to clear  recently created sql parse and execution plan

SQL > alter system flush shared_pool;

There is two more alternatives may be helpful for us.

1.Find the all tables and views with their tables that are loaded in the buffer cache. This info is necessary for the tablespaces. Reactivate all table spaces ( make offline then online to invlidate all related blocks on these tablespaces) .

syntax:

'ALTER TABLESPACE <tablespace_name> OFFLINE;'
'ALTER TABLESPACE <tablespace_name> ONLINE;'

2.Shutdown and start the db to clear the SGA ..:)

References:

http://www.adp-gmbh.ch/ora/sql/alter_system.html

http://forums.oracle.com/forums/thread.jspa?threadID=38497

explain plans

•July 23, 2007 • Leave a Comment

1.Explain plan for command

Main advantage is that it does not actually run the query – just parses the sql. This means that it executes quickly. In the early stages of tuning explain plan gives you an idea of the potential performance of your query without actually running it. You can then make a judgement as to any modifications you may choose to make.

For example:

SQL> explain plan for
2 select empno,ename from emp where empno=10;Explained

Then, use this operation to learn explain output :

SQL> select plan_table_output from table(dbms_xplan.display(‘plan_table’,null,’serial’));

You can see the output now:

SQL> select plan_table_output from table(dbms_xplan.display(‘plan_table’,null,’serial’));

PLAN_TABLE_OUTPUT
——————————————————————————–
Plan hash value: 4120447789
——————————————————————————–
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)
——————————————————————————–
| 0 | SELECT STATEMENT | | 1 | 25 | 1 (0)
| 1 | TABLE ACCESS BY INDEX ROWID| EMP | 1 | 25 | 1 (0)
|* 2 | INDEX UNIQUE SCAN | EMP_EMPNO_PK | 1 | | 1 (0)
——————————————————————————–
Predicate Information (identified by operation id):
—————————————————
2 – access(“EMPNO”=10)
14 rows selected

2.Autotrace

Autotrace can be configured to run the sql & gives a plan and statistics afterwards or just give you an explain plan without executing the query.

3.Tkprof

Analyzes trace file




For more information :

http://www.akadia.com/services/ora_interpreting_explain_plan.html

SQL Injection

•July 23, 2007 • Leave a Comment

SQL Injection – Ersin bind kullanarak engellenecegini anlatmisti …..

This month’s question comes to us from Carson in Atlanta: I keep hearing about a security threat called “SQL injection.” What is it? What risks does it present, and how can I protect my Oracle system?

Gary Sadler of the Database Specialists team responds: SQL injection is a way of using dynamic SQL to gain access to restricted information stored in a database. SQL injection can also be used to circumvent security mechanisms in order to cause the database software to malfunction. In some cases the server on which the database runs can be impacted as well. The effects can be disastrous to system uptime and the confidentiality of the data stored in the database.

SQL injection exploits are a dime-a-dozen. Even the Oracle database itself is not immune. For example, in many Oracle 9i and even Oracle 10gR1 databases without the current Critical Patch Update, a user with just the CREATE SESSION and CREATE PROCEDURE privileges can gain DBA access very easily using SQL injection. First, the user (we’ll call him Noah) creates a function:

CREATE OR REPLACE FUNCTION NOAH.SQL_INJECT return varchar2
authid current_user as
pragma autonomous_transaction;
BEGIN
EXECUTE IMMEDIATE 'GRANT DBA TO NOAH';
RETURN '';
END;
/

Next, Noah performs the SQL injection using a commonly available Oracle PL/SQL supplied package (the name is obfuscated here):

select sys.dbms_something('''||noah.sql_inject()||''','') from dual;

Bingo! Noah is now a DBA. Pretty scary, huh? Fortunately this security hole was closed in later releases of Oracle 9i and Oracle 10g. But this is just one example of SQL injection. There are many others, and they are pretty easy to find. Some involve a particular third-party tool or Oracle functionality. Others employ a technique that can be used with a wide variety of systems including your own. Let’s look at a more commonplace example. Suppose you application runs the simple SQL statement:

SELECT name,dept FROM employee WHERE name='&Name';

Here “&Name” is a value input by the user. Instead of playing by the rules and merely inputting a name and getting back a department, the user inputs this:

x' union select name,ssn from employee where 'x'='x

This transforms your SQL statement into this:

SELECT name,dept FROM employee WHERE name='x'
UNION
SELECT name,ssn FROM employee WHERE 'x'='x'

Now instead of getting back a department for one employee as you intended, the user gets back a Social Security Number for every employee. The private information in your database has just been compromised. How can SQL injection be prevented? There’s no magic bullet, but here is a list of action items that can help limit your risk:

  • Those developing software for your company must be kept aware of the risk and held accountable for producing code that does not meet standards set by the organization’s information security policy.
  • Software should use bind variables instead of insertion of literal values wherever possible.
  • Software must validate all input from users, especially when the input data will be inserted into a query as a literal and not a bind variable value. Certain Oracle reserved words and character combinations cannot be allowed. Good candidates are ||, –, ;, SELECT, UNION, FROM, WHERE, GRANT, REVOKE, CREATE, ALTER, EXEC, INSERT, UPDATE, DELETE, DROP, and TRUNCATE.
  • When it comes to access, your mantra should be “least privilege”. It won’t earn you a lot of friends and will undoubtedly cause some stress while getting access tuned to the correct level, but if you set the right tone and expectations, people will adjust.
  • Never rely solely on application-level security. Assume that a user will find their way to the database outside of the customary channels.
  • While hackers tend to get the most press, your greatest concern should be with authorized users – employees, consultants, partners, and the like. Anyone requesting authorization to access the database should be vetted as much as possible.
  • Keep the database software patched. As exploits are discovered, Oracle releases interim software patches (a.k.a. Critical Patch Updates) and all-inclusive patchsets. Regardless of your version, take it up to the highest patch level supported for your platform. The security landscape was enhanced a great deal in Oracle 10g, so that would be the version of choice for the most security conscious.
  • Disable accounts that are not currently in use. When a new Oracle 10g database is created, all of those built-in accounts are disabled by default. That’s not the case in earlier versions, however.

The risks imposed by SQL injection attacks are greater now than ever. Take the time to discover where the vulnerabilities are in your systems. Employing basic security strategies, along with maintaining the proper level of awareness, will go a long way toward prevention.

Hasan Tonguc Yılmaz

Autotrace in SQLPLUS

•July 20, 2007 • Leave a Comment

About Autotrace

Autotrace facility is used to see the execution plans

and gives statistics for the SQL statements.

The report is generated after successful SQL DML statements.

It is useful for monitoring and tuning the performance of these statements.

Controlling the Report

You can control the report by setting the AUTOTRACE system variable.

SET AUTOTRACE OFF

- No AUTOTRACE report is generated. This is the default.

SET AUTOTRACE ON EXPLAIN

- The AUTOTRACE report shows only the optimizer execution path.

SET AUTOTRACE ON STATISTICS

- The AUTOTRACE report shows only the SQL statement execution statistics.

SET AUTOTRACE ON

- The AUTOTRACE report includes both the optimizer execution path and the SQL statement execution statistics.

SET AUTOTRACE TRACEONLY

- Like SET AUTOTRACE ON, but suppresses the printing of the user’s query output, if any.

Execution Plan

The Execution Plan shows the SQL optimizer’s query execution path.

Each line of the Execution Plan has a sequential line number. SQL*Plus also displays the line number of the parent operation.

The Execution Plan consists of four columns displayed in the following order:

Column Name Description

ID_PLUS_EXP Shows the line number of each execution step.

PARENT_ID_PLUS_EXP Shows the relationship between each step and its

parent. This column is useful for large reports.

PLAN_PLUS_EXP Shows each step of the report.

OBJECT_NODE_PLUS_EXP Shows the database links or parallel query servers

used.

Timing SQL Commands

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

Oracle provides a TIMING command for measuring the running time of SQL commands.

Then, Oracle will automatically display the elapsed wall-clock time for each SQL command you run subsequently. Note that timing data may be affected by external factors such as system load, etc.

set timing on;

set timing off;

Procedure

Step 1: Connected as the SYS database user

Run the PLUSTRACE.script on the path:

Linux : $ORACLE_HOME/sqlplus/admin

Windows : C:\oraclexe\app\oracle\product\10.2.0\server\RDBMS\ADMIN\

SQL> conn sys as sysdba

Enter password:

Connected.

SQL> @$ORACLE_HOME/sqlplus/admin/plustrce.sql

– Automatically running script

SQL>

SQL> drop role plustrace;

Role dropped.

SQL> create role plustrace;

Role created.

SQL>

SQL> grant select on v_$sesstat to plustrace;

Grant succeeded.

SQL> grant select on v_$statname to plustrace;

Grant succeeded.

SQL> grant select on v_$mystat to plustrace;

Grant succeeded.

SQL> grant plustrace to dba with admin option;

Grant succeeded.

SQL>

SQL> set echo off

– End of script

Step 2: Run the UTLXPLAN.SQL script on the path: $ORACLE_HOME/rdbms/admin

SQL> @utlxplan

SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql

Table created.

Step 3: Now, we can use the autorace facility by using the

“set autotrace on;” command.

SQL> set timing on

SQL> set autotrace on

SQL> create table t as select owner, object_name, object_id from all_objects;

Table created.

Elapsed: 00:00:03.29

SQL> select * from t;

OWNER OBJECT_NAME OBJECT_ID

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

SYS DUAL 258

PUBLIC DUAL 259

SYS SYSTEM_PRIVILEGE_MAP 311

PUBLIC SYSTEM_PRIVILEGE_MAP 313

SYS TABLE_PRIVILEGE_MAP 314

5293 rows selected.

Elapsed: 00:00:12.89

Execution Plan

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

Plan hash value: 1601196873

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

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

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

| 0 | SELECT STATEMENT | | 5293 | 242K| 8 (0)| 00:00:01 |

| 1 | TABLE ACCESS FULL| T | 5293 | 242K| 8 (0)| 00:00:01 |

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

Note

—–

- dynamic sampling used for this statement

Statistics

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

68 recursive calls

0 db block gets

412 consistent gets

24 physical reads

0 redo size

168080 bytes sent via SQL*Net to client

4248 bytes received via SQL*Net from client

354 SQL*Net roundtrips to/from client

0 sorts (memory)

0 sorts (disk)

5293 rows processed

References :

Donald K. Burleson Oracle Tips Tracing an SQL statement

http://www.remote-dba.cc/oracle_tips_tracing_sql.htm

Timing SQL Commands

http://infolab.stanford.edu/~ullman/fcdb/oracle/or-nonstandard.html

Autotrace in SQLPLUS

http://asktom.oracle.com/tkyte/article1/autotrace.html

Oracle performance analysis – Autotrace workshop

http://www.bhatipoglu.com/entry.asp?id=18

RowID Format

•July 19, 2007 • Leave a Comment

ROWID Format

An extended ROWID needs 10 bytes of storage on disk and is displayed by using 18 characters. It consists of the following components:

Data object number: Is assigned to each data object, such as table or index when it is created, and it is unique within the database

Relative file number: Is unique to each file within a tablespace

Block number: Represents the position of the block, containing the row, within the file

Row number: Identifies the position of the row directory slot in the block header

Internally, the data object number needs 32 bits, the relative file number needs 10 bits, block number needs 22 bits, and the row number needs 16 bits, adding up to a total of 80 bits or 10 bytes.

An extended ROWID is displayed using a base-64 encoding scheme, which uses six positions for the data object number, three positions for the relative file number, six positions for the block number, and three positions for the row number. The base-64 encoding scheme uses characters A-Z, a-z, 0-9, and /. This is a total of 64 characters, as in the following example:

ROWID Format (continued)

SQL> SELECT department_id, rowid FROM hr.departments;

DEPARTMENT_ID ROWID

————- ——————

10 AAABQMAAFAAAAA6AAA

20 AAABQMAAFAAAAA6AAB

30 AAABQMAAFAAAAA6AAC

40 AAABQMAAFAAAAA6AAD

50 AAABQMAAFAAAAA6AAE

60 AAABQMAAFAAAAA6AAF

In this example:

AAABQM is the data object number

AAF is the relative file number

AAAAA6 is the block number

AAA is the row number for the department with ID = 10

Restricted ROWID in Oracle7 and earlier:

Versions of the Oracle database prior to Oracle8 used the restricted ROWID format. A restricted ROWID used only six bytes internally and did not contain the data object number. This format was acceptable in Oracle7 or an earlier release because the file numbers were unique within a database. Thus, earlier releases did not permit more than 1,022 datafiles. Now it is the limit for a tablespace.

Even though Oracle8 removed this restriction by using tablespace-relative file numbers, the restricted ROWID is still used in objects like nonpartitioned indexes on nonpartitioned tables where all the index entries refer to rows within the same segment.

Locating a row using ROWID:

Because a segment can only reside in one tablespace, by using the data object number, the Oracle server can determine the tablespace that contains a row.

The relative file number within the tablespace is used to locate the file, the block number is used to locate the block containing the row, and the row number is used to locate the row directory entry for the row.

The row directory entry can be used to locate the beginning of the row.

Thus, ROWID can be used to locate any row within a database.

structures of rows

Structure of a Row

Row data is stored in database blocks as variable-length records. Columns for a row are generally stored in the order in which they are defined and any trailing NULL columns are not stored.

Note: A single byte for column length is required for non trailing NULL columns. Each row in a table has:

Row header: Used to store the number of columns in the row, the chaining information, and the row lock status

Row data: For each column, the Oracle server stores the column length and value (One byte is needed to store the column length if the column will require more than 250 bytes of storage in which case three bytes will be used for column length. The column value is stored immediately following the column length bytes.)

Adjacent rows do not need any space between them. Each row in the block has a slot in the row directory. The directory slot points to the beginning of the row.

 Sent by Hasan Tonguc Yılmaz

SQL Developer

•July 19, 2007 • Leave a Comment

Herkes PL/SQL Developer ve Toad imkani bulamayabilir, ama SQL Developer ucretsiz ve iyi bir alternatif sunuyor bence -

http://technology.amis.nl/blog/?p=2327

http://www.oracle.com/technology/products/database/sql_developer/index.html

 

 

 



Sent by Hasan Tonguc Yilmaz

Synonyms

•July 19, 2007 • Leave a Comment

 

When you reference an object in a SQL command that is owned by another user, you must preface the object name with the owner’s username.

 

SELECT * FROM scott.dept ;

 

A synonym is an alternate name for an object that references the owner name, as well as the object name.

 

Public Synonyms

 

A public synonym can be created only by a DBA or by a user who has the privilege to create public synonyms.

 

CREATE synonym_name FOR owner_name.tablename.

 

CREATE PUBLIC SYNONYM public_dept

FOR scott.dept;

SELECT *  FROM

Public_dept;

 

Private Synonyms

 

When a user creates a private synonym, only that user can use the private synonym.

 

CREATE SYNONYM synonym_name FOR owner_name.object_name

 

CREATE SYNONYM private_dept

FOR scott.dept;

Indexes

•July 19, 2007 • Leave a Comment

 

A database index is a table that contains data values, along with a corresponding column that specifies the physical locations of the records (ROWID) that contain the associated sorted data values.

You can find rowid column for every record in each table.

 

SELECT rowid, total_hours FROM project_consultant

ORDER BY total_hours;

 

Oracle automatically creates an index on the primary key of the table.

Managing records in an indexed table can be slow process because the DBMS must modify the index every time the record values changed.

 

Creating an Index

 
CREATE INDEX index_name ON tablename (index_column);

Index name should be index_tablename_fieldname.

 

CREATE INDEX project_consultant_total_hours

ON project_consultant (total_hours);

Composite indexes can contain multiple columns that the DBMS can use for identifying the row location.

 

CREATE INDEX index_name ON tablename ( index_column1, index_column2, …);


CREATE INDEX consultant_skill_skill_id_cert

ON consultant_skill (skill_idi certification);

View Index Information Using the Data Dictionary Views

You can retrieve the names of the indexes in your user schema by querying the USER_INDEXES data dictionary view.

 

SELECT index_name

FROM user_indexes;

Dropping an Index

DROP INDEX index_name;

Database Views

•July 19, 2007 • Leave a Comment

 

A view does not physically exist in the database. It is derived from other database tables. When the data in its source table is updated , the view reflects the updates as well.

If structure of a view’s source table is altered, or if a view’s source table is dropped, then the view becomes invalid and can no longer be used until it is dropped and re-created or replaced.

 

Creating and Manipulating Simple Views

CREATE VIEW view_name AS sql_query; 
The view name must follow the Oracle naming standards.
The view name can not already exist in the user’s database schema.

You must have sufficient object privileges are related with the view to manage the records.

CREATE OR REPLACE VIEW view_name AS Sql_query;

 

 

CREATE VIEW faculty_view as

SELECT f_id, f_last, f_first, f_mi, loc_id, f_phone, f_rank

FROM faculty


 

SELECT f_last, f_first, bldg_code, room

FROM faculty_view, location

WHERE faculty_view.loc_id = location.loc_id;

 

Creating and Manipulating Complex Views

 

Complex views, unlike simple views, cannot be used to directly manage data in the underlying database tables.

 

CREATE VIEW inventory_view AS

SELECT item_desc, item_size, color, price, qoh, price*qoh AS value

FROM inventory, item

WHERE item.item_id = inventory.item_id

ORDER BY item_desc;

 

Dropping Views

 

DROP VIEW view_name;

 

Using Data Dictionary Views to Retrieve Information about the Views

 

Dictionary views: All_views

                               User_views

 

You can only see information about views for which you have been granted object privileges.

SELECT view_name

FROM ALL_VIEWS

WHERE owner = ‘SYSTEM’;