Showing posts sorted by date for query partition. Sort by relevance Show all posts
Showing posts sorted by date for query partition. Sort by relevance Show all posts

Jul 27, 2025

Vector Search and Vector Index - working steps (demo)

 -- Setup Oracle 23ai 

Click Here : Oracle 23ai Database setup

Small Introduction about vector Database and Vector Search:

- Vector Database 

A vector database is a specialized type of database designed to store, index, and query data represented as high-dimensional vectors, also known as vector embeddings. These embeddings are numerical representations of various data types, such as text, images, audio, or other complex objects, generated by machine learning models like large language models (LLMs)

- Vector Search:

Vector search is a method of information retrieval that leverages these vector embeddings to find data points that are semantically similar to a given query. Instead of relying on exact keyword matches, vector search calculates the "distance" or "similarity" between the query vector and the vectors stored in the database. This allows for more intelligent and context-aware searches, enabling use cases like:

1) Semantic Search
2) Image and Audio Recognition
3) Retrieval-Augmented Generation (RAG)
4) Recommendation Systems

Vector databases and vector search are crucial components in modern AI applications, facilitating efficient and effective handling of unstructured and semi-structured data for various machine learning tasks.

Most Important part in AI is Retrieval-augmented generation (RAG). RAG is a technique that enhances the performance of large language models (LLMs) by combining them with an external knowledge base. Instead of relying solely on their pre-trained knowledge, RAG systems retrieve relevant information from external sources and incorporate it into the generation process, resulting in more accurate, informed, and up-to-date responses. 

Note: Create your own file system and directories to test the scenarios

Let us start the POC on loading LLM, Creating vector and generate test case on vector search.

Step#01 - create a directory to hold the model, download it, and unzip the model into that directory.

$ mkdir -p /u04/23ai_activity/models
$ cd /u04/23ai_activity/models
$ wget https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/VBRD9P8ZFWkKvnfhrWxkpPe8K03-JIoM5h_8EJyJcpE80c108fuUjg7R5L5O7mMZ/n/adwc4pm/b/OML-Resources/o/all_MiniLM_L12_v2_augmented.zip

unzip -oq all_MiniLM_L12_v2_augmented.zip

Step#02 - Connect to the database, create a test user, create a directory object pointing to the physical directory, and grant access to it for our test user.

SQL> alter session set container=FREEPDB1;
Session altered.

- create user to test scenarios ( use strong password for the user)

create user if not exists testuser1 identified by testuser1 quota unlimited on users;
grant create session, db_developer_role, create mining model to testuser1;
create or replace directory model_dir as '/u04/23ai_activity/models';
grant read, write on directory model_dir to testuser1;



Step#3 - Now load the model into the database using the DBMS_VECTOR package.

sqlplus /nolog
conn testuser1/testuser1@//localhost:1521/freepdb1

SQL>
begin
  dbms_vector.drop_onnx_model (
    model_name => 'ALL_MINILM_L12_V2',
    force => true);
  dbms_vector.load_onnx_model (
    directory  => 'model_dir',
    file_name  => 'all_MiniLM_L12_v2.onnx',
    model_name => 'ALL_MINILM_L12_V2');
end;
/
PL/SQL procedure successfully completed.


- Now  see the model information in the USER_MINING_MODELS view.

column model_name format a30
column algorithm format a10
column mining_function format a15
select model_name, algorithm, mining_function
from   user_mining_models
where  model_name = 'ALL_MINILM_L12_V2';
MODEL_NAME                     ALGORITHM  MINING_FUNCTION
------------------------------ ---------- ---------------
ALL_MINILM_L12_V2              ONNX       EMBEDDING


Step#4 - Generating Vectors (VECTOR Data Type)

Generate vectors using the VECTOR_EMBEDDING function. In the following example we generate a vector for the text "Quick test". As you can see, the resulting vector is really big considering the size of the text.

set lines 160
set long 1000000
select vector_embedding(all_minilm_l12_v2 using 'Quick test' as data) AS my_vector;
MY_VECTOR
----------------------------------------------------------------------------------------------------------------------------------------------------------------
[-3.86444256E-002,7.27762803E-002,-6.99377712E-003,-7.29618035E-003,8.81512091E-003,-6.36086613E-002,4.39666817E-003,-4.20215651E-002,-1.32307202E-001,-5.837616
05E-003,-1.3236966E-002,-1.62914731E-002,6.54898351E-003,-4.983522E-002,-1.98450536E-002,-4.69920225E-002,1.03937663E-001,-8.96753445E-002,-2.77861813E-003,4.13
947664E-002,-6.51626661E-002,-1.09901905E-001,-8.73053819E-003,2.533352E-002,-1.42030632E-002,-2.42071245E-002,1.91591978E-002,4.93748812E-003,6.30869251E-003,-
1.24127813E-001,-7.17297941E-003,3.7317384E-002,4.97635901E-002,4.52162437E-002,1.49683114E-002,-2.21795831E-002,-3.67936082E-002,-6.20233943E-004,7.16803819E-0
02,5.33913262E-003,1.92087106E-002,-9.91346017E-002,3.90679464E-002,2.22725421E-002,5.04363105E-002,1.81943253E-002,5.34031466E-002,1.44161871E-002,-1.99907795E
-002,-1.20323608E-002,-2.63888389E-002,-4.14667316E-002,6.2473774E-002,-4.68838662E-002,1.16748568E-002,-2.43180972E-002,-3.11982706E-002,-7.5750039E-003,2.2546
6359E-002,-4.17359956E-002,1.23237111E-002,4.31706831E-002,-7.83750787E-002,1.24918511E-002,5.42060807E-002,4.33742851E-002,2.52278382E-003,-1.15482137E-002,-9.
98658361E-004,-2.12613102E-002,1.00960173E-002,3.17986645E-002,-1.13146752E-002,-1.26893371E-002,2.66182758E-002,-7.50683714E-003,-3.70341949E-002,1.94851588E-0
02,-2.9213747E-002,-2.61210538E-002,2.86212545E-002,-9.15900841E-002,1.50552345E-002,-4.98168021E-002,2.29324233E-002,7.82517716E-003,4.22972552E-002,3.37974802
E-002,-4.2345725E-002,-6.32970557E-002,3.84949856E-002,-1.93851739E-002,1.96233811E-003,-3.91593436E-004,7.80334743E-003,5.63595518E-002,4.45814878E-002,-4.9701
6348E-002,1.36384079E-002,2.76547611E-001,6.3580215E-002,-1.69337653E-002,-3.25948671E-002,2.74621621E-002,-1.84809547E-002,-3.58916223E-002,3.18280957E-003,-3.


 
===========
EXAMPLE-2
===========
Step#1 - Download below csv file from hugging face

https://huggingface.co/datasets/ygorgeurts/movie-quotes/resolve/main/movie_quotes.csv?download=true -O movie_quotes.csv

Step#2 - Connect to the database and create a new table from the CSV file of movie quotes.

sqlplus /nolog
conn testuser1/testuser1@//localhost:1521/freepdb1
drop table if exists movie_quotes purge;
create table movie_quotes as
select movie_quote, movie, movie_type, movie_year
from   external (
         (
           movie_quote  varchar2(400),
           movie        varchar2(200),
           movie_type   varchar2(50),
           movie_year   number(4)
         )
         type oracle_loader
         default directory model_dir
         access parameters (
           records delimited by newline
           skip 1
           badfile model_dir
           logfile model_dir:'moview_quotes_ext_tab_%a_%p.log'
           discardfile model_dir
           fields csv with embedded terminated by ',' optionally enclosed by '"'
           missing field values are null
           (
             movie_quote char(400),
             movie,
             movie_type,
             movie_year
           )
        )
        location ('movie_quotes.csv')
        reject limit unlimited
      );
  
  
Table created.
SQL>

SQL> desc movie_quotes
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 MOVIE_QUOTE                                        VARCHAR2(400)
 MOVIE                                              VARCHAR2(200)
 MOVIE_TYPE                                         VARCHAR2(50)
 MOVIE_YEAR                                         NUMBER(4)
SQL>

Step#4 - add a new column to hold the vector data for each movie quote. we are using the new VECTOR data type.

SQL> alter table movie_quotes add (
  movie_quote_vector vector
);  
Table altered.
SQL> desc movie_quotes
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 MOVIE_QUOTE                                        VARCHAR2(400)
 MOVIE                                              VARCHAR2(200)
 MOVIE_TYPE                                         VARCHAR2(50)
 MOVIE_YEAR                                         NUMBER(4)
 MOVIE_QUOTE_VECTOR                                 VECTOR(*, *)
SQL>


Step#5 - populate the new column by generating vectors from the movie quotes.


SQL> update movie_quotes
set    movie_quote_vector = vector_embedding(ALL_MINILM_L12_V2 using movie_quote as data);
732 rows updated.
SQL> commit;
Commit complete.


Step#5 - Vector Search using VECTOR_DISTANCE

Now perform a search using the VECTOR_DISTANCE function. 
This accepts two vectors and as the name suggests, returns a distance between them. 
Since the model we used generates vectors for text data, 
we would expect the vector distance to be smaller for two vectors that are similar. 
In the following examples we create a vector from our search text and order the output 
of the query by the vector distance between our search text and the quote text.
First we ask for "Films with motivational speaking in them".


SQL> variable search_text varchar2(100);
exec :search_text := 'Films with motivational speaking in them';SQL>
PL/SQL procedure successfully completed.
SQL>
set pages 100
set linesize 200
column movie format a50
column movie_quote format a100
SELECT vector_distance(movie_quote_vector, (vector_embedding(all_minilm_l12_v2 using :search_text as data))) as distance,
       movie,
       movie_quote
FROM   movie_quotes
order by 1
fetch approximate first 5 rows only;


OUT-PUT:
  
DISTANCE MOVIE                                              MOVIE_QUOTE
---------- -------------------------------------------------- ----------------------------------------------------------------------------------------------------
6.786E-001 Once Upon a Time in Hollywood                      That was the best acting i've ever seen in my whole life.
6.979E-001 Dead Poets Society                                 You must strive to find your own voice because the longer you wait to begin, the less likely you are
                                                               going to find it at all.
7.169E-001 The Pursuit of Happyness                           Walk that walk and go forward all the time. Don't just talk that talk, walk it and go forward. Also,
                                                               the walk didn't have to be long strides; baby steps counted too. Go forward.
7.186E-001 Joker                                              My mother always tells me to smile and put on a happy face. She told me I had a purpose to bring lau
                                                              ghter and joy to the world.
7.234E-001 Blazing Saddles                                    Men, you are about to embark on a great crusade to stamp out runaway decency in the west. Now you me
                                                              n will only be risking your lives, whilst I will be risking an almost certain Academy Award nominati
                                                              on for Best Supporting Actor.




Next we ask for "Films about war".
-------------------------------

variable search_text varchar2(100);
exec :search_text := 'Films about war';
set linesize 200
column movie format a50
column movie_quote format a100
SELECT vector_distance(movie_quote_vector, (vector_embedding(all_minilm_l12_v2 using :search_text as data))) as distance,
       movie,
       movie_quote
FROM   movie_quotes
order by 1
fetch approximate first 5 rows only;

  DISTANCE MOVIE                                              MOVIE_QUOTE
---------- -------------------------------------------------- ----------------------------------------------------------------------------------------------------
5.682E-001 Dr. Strangelove                                    Gentlemen, you can't fight in here! This is the War Room!
6.346E-001 Blazing Saddles                                    Men, you are about to embark on a great crusade to stamp out runaway decency in the west. Now you me
                                                              n will only be risking your lives, whilst I will be risking an almost certain Academy Award nominati
                                                              on for Best Supporting Actor.
6.587E-001 Fury                                               Ideals are peaceful; history is violent.
7.243E-001 The Kill Team                                      You give me your loyalty, and I?ll guarantee that each and every one of you will have a chance to be
                                                               a warrior, to actually be a part of history.
7.253E-001 Dr. No                                             Bond. James Bond



Step#6 - (Optional) Create a Vector Index 

If we want to create a vector index, we must set the VECTOR_MEMORY_SIZE parameter for the root container. The amount of memory we need depends on the size and complexity of the data being indexed.

conn / as sysdba
SQL> show parameter vector_memory_size;
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
vector_memory_size                   big integer 0

alter system set vector_memory_size = 1G scope=spfile;
shutdown immediate;
startup;


-- There are two types of vector indexes.
-- Neighbor Partition Vector Indexes
-- In-Memory Neighbor Graph Vector Index

conn testuser1/testuser1@//localhost:1521/freepdb1
drop index if exists movie_quotes_vector_idx;

-- Neighbor Partition Vector Index

create vector index movie_quotes_vector_idx on movie_quotes(movie_quote_vector) organization neighbor partitions
distance cosine
with target accuracy 95;

drop index if exists movie_quotes_vector_idx;

-- In-Memory Neighbor Graph Vector Index

create vector index movie_quotes_vector_idx on movie_quotes(movie_quote_vector) organization inmemory neighbor graph
distance cosine
with target accuracy 95;

Note:  Vectors are big. This has to be taken into account from both a storage perspective, and a memory perspective, especially when creating vector indexes.

-----
-- Search the query again
variable search_text varchar2(100);
exec :search_text := 'Films about war';
set linesize 200
column movie format a50
column movie_quote format a100
SELECT vector_distance(movie_quote_vector, (vector_embedding(all_minilm_l12_v2 using :search_text as data))) as distance,
       movie,
       movie_quote
FROM   movie_quotes
order by 1
fetch approximate first 5 rows only;

Now see the difference when you have large amount of data.

Follow my blog and share with others.


Jan 27, 2022

Oracle Database 19c New features

Installation and Upgrades

1.        Simplified Image based installation, RPM Based Installation, RPM method with Vagrant Virtual box and via ansible playbook
https://docs.oracle.com/en/database/oracle/oracle-database/19/install-and-upgrade.html               

2.       Docker Container for Oracle 19c

3.        Auto Upgrade Utility for Oracle Database
https://docs.oracle.com/en/database/oracle/oracle-database/19/upgrd/using-autoupgrade-oracle-database-upgrades.html    

4.       DryRun mode for GridSetup in Clusterware Installation
https://docs.oracle.com/en/database/oracle/oracle-database/19/cwlin/running-oui-in-dry-run-upgrade-mode.html       

 General

1.        Auto Space Management for Flashback Logs in the FRA.

2.       Multimodel partitioning with Hybrid partitioning allowing some partitions in the database and some as external partitions

3.        Schema-only accounts

4.       Flush Metadata Cache for Passwords

5.       Hybrid Partitioned Tables - to integrate internal partitions and external partitions into a single partition table.  partitions to reside in both Oracle Database segments and in external files and sources

Support:

Oracle 19c database release is a Long Term Release with 5 years of Premier Support followed by 3 years of Extended Support.

 

Pluggable Databases

1.        From Oracle 19 onwards, UNDO_RETENTION parameter can be set separately in each PDB, provided local undo is being used.

2.       ADDM Analysis at PDB Level

3.        Creation Duplicate of an Oracle Database using CreateDuplicateDB command, in DBCA Silent Mode

4.       Ability to Create a PDB by Cloning a Remote PDB Using DBCA in Silent Mode

5.       Ability to relocate a PDB to another CDB Using DBCA in Silent Mode

 Data Pump

1.        Oracle Data Pump Ability to Exclude ENCRYPTION Clause on Import - new transform parameter OMIT_ENCRYPTION_CLAUSE

2.       Oracle Data Pump Support for Resource Usage Limitations - new parameter MAX_DATAPUMP_PARALLEL_PER_JOB

3.        Oracle Data Pump Test Mode for Transportable Tablespaces (TTS)

4.       Oracle Data Pump Prevents Inadvertent Use of Protected Roles -  new ENABLE_SECURE_ROLES parameter is available

Performance

1.        SQL Quarantine (restricted to Enterprise Edition on Engineered Systems) - Starting Oracle 19c, Cancelling a runaway query is helpful to prevent wasting system resources, but if that problem query is run repeatedly, it could still result in a considerable amount of wasted resources. SQL Quarantine solves this problem by quarantining cancelled SQL statements, so they can't be run multiple times. ex: cpu limit, elapsed_time limit etc. To define the thresholds you can use DBMS_SQLQ package.quarantine configuration for an execution plan for a SQL statement

2.       Automatic Indexing - Manage Auto Indexes with Advisory task like MOnitor, Capture, Identify, Verify, Decide -  to enable auto index mode is below, we have options "Implement", "Report-Only", "OFF".

3.        select * from dba_auto_index_config;

4.       SQL Statement Diagnosability with SQL Advisor repair and SQL Test case for procedures

5.       Automatic Database Diagnostic Monitor (ADDM) Support for Pluggable Databases (PDBs)

6.       Realtime statistics for DML Operations - Oracle Database 19c introduces real-time statistics, which extend online support to conventional DML statements

7.        Statistics Collection on custom frequency automatically - From 19c onwards,  High-frequency automatic optimizer statistics collection complements the standard statistics collection job

8.       Workload Capture and Replay in a PDB

Data Guard

1.        Replicate Restore Points from Primary to Standby

2.       Dynamically change Fast-Start Failover (FSFO) target standby database to another standby database in the target list without disabling FSFO.

3.        Automatic Flashback of Standby

4.       Re-creation of broker configuration

5.       Propagate Restore Points from Primary to Standby site

6.       DML redirect to standby/ADG for read-mostly applications

7.        Simplified Dataguard broker parameter configurations

8.       Flashback Standby Database when Primary Database is Flashed Back - Oracle 19c onwards, DBA can put the standby database in MOUNT mode without managed recovery and then flashback primary database; the standby will also be reverted, thus keeping it in sync with the primary.

9.       Observe Only Mode for Data Guard Broker's Fast-Start Failover (FSFO)

10.    Oracle Data Guard Multi-Instance Redo Apply Works with the In-Memory Column Store

11.     Finer Granularity Supplemental Logging for logical standby databases

New tables/views in Oracle 19c Database

dba_auto_index_config

dba_sql_quarantine

V$SQL_TESTCASES

DBA_REGISTRY_BACKPORTS

New packages in 19c Database Release 1

dbms_auto_index

dbms_auto_index_internal

DBMS_SQLQ


Apr 1, 2020

Interval partitioning

I received a request to add a partition automatically on every data based on date. Assume up to 2000 one partition but after for each date partition to be created based on a date column.

Here is the example:

CREATE TABLE sales
  ( prod_id       NUMBER(6)
  , time_id       DATE
  , quantity_sold NUMBER(3)
  )
 PARTITION BY RANGE (time_id) INTERVAL (NUMTODSINTERVAL(1,'DAY'))
 (PARTITION before_2000 VALUES LESS THAN (TO_DATE('01-JAN-2000','dd-MON-yyyy'))
  );

-- Your test data like some thing like this
insert into sales values(9,'9-Jan-2005',100);
commit;

-- To see all partition tables

select * from USER_TAB_PARTITIONS where table_name='SALES';

Jan 11, 2018

Install Oracle OEM agent 13c using EM CLI

In this post we will see how to install OEM agent 13c on any target host.

My OMS server host name : oemhost ( oemhost.oracle.com)
My target host is here : example

Step:1 - Find your supported platform details and OMS version

[oracle@oemhost bin]$ pwd
/u01/app/OEM/Middleware13c/bin
[oracle@oemhost bin]$ ./emcli login -username=gmohapatra
Enter password : 

Login successful
[oracle@oemhost bin]$ ./emcli sync
Synchronized successfully
[oracle@oemhost bin]$ ./emcli get_supported_platforms
-----------------------------------------------
Version = 13.2.0.0.0
 Platform = Linux x86-64
-----------------------------------------------
Version = 13.2.0.0.0
 Platform = Microsoft Windows x64 (64-bit)
-----------------------------------------------
Version = 12.1.0.4.0
 Platform = Linux x86-64
-----------------------------------------------
Platforms list displayed successfully.
[oracle@oemhost bin]$ 


Step:2 - Create agent image. You can create in your OMS and move to target host or you can install emcli client on target host and run same installation steps:

In OMS server downloaded the agent for the platform.

[oracle@oemhost bin]$ ./emcli get_agentimage -destination=/tmp/agentinstaller -platform="Linux x86-64" -version="13.2.0.0.0"
 === Partition Detail ===
Space free : 4 GB
Space required : 1 GB
Check the logs at /u01/app/OEM/gc_inst1/em/EMGC_OMS1/sysman/emcli/setup/.emcli/get_agentimage_2018-01-08_14-33-00-PM.log
Downloading /tmp/agentinstaller/13.2.0.0.0_AgentCore_226.zip
File saved as /tmp/agentinstaller/13.2.0.0.0_AgentCore_226.zip
Downloading /tmp/agentinstaller/13.2.0.0.0_Plugins_226.zip
File saved as /tmp/agentinstaller/13.2.0.0.0_Plugins_226.zip
Downloading /tmp/agentinstaller/unzip
File saved as /tmp/agentinstaller/unzip
Executing command: /tmp/agentinstaller/unzip /tmp/agentinstaller/13.2.0.0.0_Plugins_226.zip -d /tmp/agentinstaller
Exit status is:0
Agent Image Download completed successfully.
[oracle@oemhost bin]$ 


Step-3: Now let’s scp the software to our target server or Transfer it and unzip it. Then go to the installer location. Then run below command. 

$./agentDeploy.sh AGENT_BASE_DIR=/u01/app/oracle/product/agent13c \
-ignorePrereqs \
-invPtrLoc /u01/app/OraInventory/oraInst.loc  \
AGENT_PORT=3872 \
EM_UPLOAD_PORT=4903 \
OMS_HOST=oemhost.oracle.com \
ORACLE_HOSTNAME=example \
AGENT_INSTANCE_HOME=/u01/app/oracle/product/agent13c/agent_13.2.0.0.0 \ -- optional
AGENT_REGISTRATION_PASSWORD="world123" \
SCRATCHPATH=/home/oracle/tmp

OR

You can create a .rsp ( response file and run like below):

-- see the values set in agent.rsp response file:

$ cat agent.rsp | grep -v ^# | grep -v ^$
OMS_HOST=oemhost.oracle.com
EM_UPLOAD_PORT=4903
AGENT_REGISTRATION_PASSWORD=world123
AGENT_PORT=3872
EM_INSTALL_TYPE="AGENT"

$/u01/app/oracle/product/agent13c/agentDeploy.sh AGENT_BASE_DIR=/u01/app/oracle/product/agent13c RESPONSE_FILE=/u01/app/oracle/product/agent13c/agent.rsp


Note:
If you are getting below error then go with recommended fix:

Error msg:

SEVERE:emctl secure agent command has failed with status=1
Agent configuration has failed
Waiting for agent targets to get promoted...

Fix:

Reset the password of "AGENT_REGISTRATION_PASSWORD"

Setup --> Security --> Registration Passwords --> create

Step:4 - Execute the root.sh as given in the log from # ( root) user

# /u01/app/oracle/product/agent13c/agent_13.2.0.0.0/root.sh

Step-5: Check the agent status now:

[oracle@example bin]$ pwd
/u01/app/oracle/product/agent13c/agent_13.2.0.0.0/bin
[oracle@example bin]$ 
[oracle@example bin]$ ./emctl status agent
Oracle Enterprise Manager Cloud Control 13c Release 2  
Copyright (c) 1996, 2016 Oracle Corporation.  All rights reserved.
---------------------------------------------------------------
Agent Version          : 13.2.0.0.0
OMS Version            : 13.2.0.0.0
Protocol Version       : 12.1.0.1.0
Agent Home             : /u01/app/oracle/product/agent13c/agent_inst
Agent Log Directory    : /u01/app/oracle/product/agent13c/agent_inst/sysman/log
Agent Binaries         : /u01/app/oracle/product/agent13c/agent_13.2.0.0.0
Core JAR Location      : /u01/app/oracle/product/agent13c/agent_13.2.0.0.0/jlib
Agent Process ID       : 29272
Parent Process ID      : 29240
Agent URL              : https://example.oracle.com:3872/emd/main/
Local Agent URL in NAT : https://example.oracle.com:3872/emd/main/
Repository URL         : https://oemhost.oracle.com:4903/empbs/upload
Started at             : 2018-01-10 14:15:40
Started by user        : oracle
Operating System       : Linux version 2.6.32-358.el6.x86_64 (amd64)
Number of Targets      : 2
Last Reload            : (none)
Last successful upload                       : 2018-01-10 14:22:31
Last attempted upload                        : 2018-01-10 14:22:31
Total Megabytes of XML files uploaded so far : 0.28
Number of XML files pending upload           : 0
Size of XML files pending upload(MB)         : 0
Available disk space on upload filesystem    : 9.78%
Collection Status                            : Collections enabled
Heartbeat Status                             : Ok
Last attempted heartbeat to OMS              : 2018-01-10 14:23:47
Last successful heartbeat to OMS             : 2018-01-10 14:23:47
Next scheduled heartbeat to OMS              : 2018-01-10 14:24:47

---------------------------------------------------------------
Agent is Running and Ready
[oracle@example bin]$ 

Dec 14, 2017

10 points may not be used by Oracle DBA

1) ORADEBUG SUSPEND | RESUME | WAKEUP

SUSPEND command:
This command suspends the current process. First select a process using SETORAPID or SETOSPID
Do not use SETMYPID as the current ORADEBUG process will hang and cannot be resumed even from another ORADEBUG process.

e.g.,
ORADEBUG SUSPEND

RESUME command:
resumes the current process.
While the process is suspended ORADEBUG can be used to take dumps of the current process state e.g. global area, heap, subheaps etc.

e.g.,
ORADEBUG RESUME

WAKEUP command
To wake up a process use:

ORADEBUG WAKEUP pid

For example to wake up SMON, first obtain the PID using:
SELECT pid FROM v$process
WHERE addr =
(
    SELECT paddr FROM v$bgprocess
    WHERE name = 'SMON'
);

If the PID is 6 then send a wakeup call using:
ORADEBUG WAKEUP 6

e.g.,
Suspend a running process
SQL> oradebug setorapid 12
Unix process pid: 10131, image: oracle@localhost.localdomain (TNS V1-V3)
SQL> oradebug suspend
Statement processed.

Resume a process
SQL> oradebug resume
Statement processed.

If you have trace turned on a suspended and resume session you will see the following messages in the trace file.
....
FETCH #5:c=54992,e=55962,p=0,cr=2334,cu=0,mis=0,r=1,dep=1,og=1,tim=1249098751175228
EXEC #5:c=0,e=72,p=0,cr=0,cu=0,mis=0,r=0,dep=1,og=1,tim=1249098751175408
Received ORADEBUG command ‘suspend’ from process Unix process pid: 22990, image:
*** 2017-12-14 21:12:34.268
Received ORADEBUG command ‘resume’ from process Unix process pid: 22990, image:
FETCH #5:c=58991,e=32316703,p=0,cr=2334,cu=0,mis=0,r=1,dep=1,og=1,tim=1249098783492125
EXEC #5:c=0,e=71,p=0,cr=0,cu=0,mis=0,r=0,dep=1,og=1,tim=1249098783492321
....

3) SQL Full Text: Which view I will use? v$sql | v$sqlarea | v$sqlstats

The column definition for columns in V$SQLSTATS are identical to those in the V$SQL and V$SQLAREA views. However, the V$SQLSTATS view differ from V$SQL and V$SQLAREA in that it is faster, more scalable, and has a greater data retention (the statistics may still appear in the view, even after the cursor has been aged out of the shared pool).

3) DESC command can be used inside SQL query to view dynamic result instead of cancel the whole query and re-write:

e.g.,
SQL> select TABLE_NAME,INDEX_NAME,LAST_ANALYZED
  2  from dba_indexes
  3  where
  4  #desc dba_indexes
 Name                                                              Null?    Type
 ----------------------------------------------------------------- -------- --------------------------------------------
 OWNER                                                             NOT NULL VARCHAR2(128)
 INDEX_NAME                                                        NOT NULL VARCHAR2(128)
 INDEX_TYPE                                                                 VARCHAR2(27)
 TABLE_OWNER                                                       NOT NULL VARCHAR2(128)
 TABLE_NAME                                                        NOT NULL VARCHAR2(128)
 TABLE_TYPE                                                                 VARCHAR2(11)
 LAST_ANALYZED                                                              DATE
 DEGREE                                                                     VARCHAR2(40)

  4  OWNER='SCOTT';

TABLE_NAME                    INDEX_NAME                                    LAST_ANALYZED
EMP                                       empid_pk                                           07-MAR-17
DEPT                                      deptno_pk                                         07-MAR-17
…..                                         
SQL>

4) Transaction commit when exiting SQL*Plus

if the case of exit without commit from sqlplus, the running transaction commit or rollback??
Answer will be Yes|no. It depends upon what the exitcommit parameter is set to!

To see current setting:
e.g.,
SQL> sho exitcommit
exitcommit ON                  (default)

To OFF:
SET EXITCOMMIT OFF;  ( this makes you “rollback” on exit)


5) Estimating Cardinalities using GATHER_PLAN_STATISTICS hint ( Oracle 10g & above)

If we add the GATHER_PLAN_STATISTICS hint to our simple SQL statement we should be able to see the actual cardinality of each operation at execution time alongside the Optimizer estimates for each cardinality in the plan.
e.g.,
SELECT     /*+ GATHER_PLAN_STATISTICS */ p.prod_name, SUM(s.quantity_sold)
FROM       sales s, products p
WHERE      s.prod_id =p.prod_id
AND        p.prod_desc = 'Consumables'
GROUP By p.prod_name ;
…..
SQL> SELECT *
FROM table(DBMS_XPLAN.DISPLAY_CURSOR(FORMAT=>'ALLSTATS LAST'));



The FORMAT parameter value 'ALLSTATS LAST' requests that the execution statistics of the last execution of the cursor be shown.

In order to see the A-Rows values for all of the operations in the plan you would have to use the FORMAT value  'ALLSTATS ALL', which will show you the execution statistics for ALL executions of the cursor. Be careful here as the values in the A-Rows column is now cumulative (incremented on every execution). The more the statement is executed the higher the values in the A-Rows column will become. This FORMAT will also show you a lot more columns in the execution plan.

6. Create index with COMPRESS:

People have often commented to me that Table Compression (and Advanced Row Compression) are  great at helping to reduce the storage footprint of an Oracle database by a factor of 2x-5x, but Oracle shouldn’t forget about the indexes.

In my experience, indexes often take up to 50% of the total database space and it is not uncommon to have 10-20 indexes on a single table (in extreme cases, It may 100 indexes per table).

Syntax:
CREATE INDEX idx_name ON table_name(col1, col2, col3) COMPRESS [<prefix_col_length>] ;

e.g.,
create index idx_test product(product_type,product_color,manufacture_date) compress 2;

The <prefix_col_length> after the COMPRESS keyword denotes how many columns to compress. The default (and the maximum) prefix length for a non-unique index is the number of key columns, and the maximum prefix length for a unique index is the number of key columns minus one.

Prior to Oracle 11g, it is risk if prefix columns are defined properly. You may have following issues:
a)       there is a small CPU overhead to reconstruct the key column values during index lookup or scans
b)      running ANALYZE INDEX takes an exclusive lock on the table, effectively making the table “offline” for this period
c)       Not useful if prefix columns are unique in a block
d)      You cannot compress your Functional Indexes with Advanced Index Compression.
e)      Bitmap indexes can't be compressed.


On partition Table:
CREATE INDEX my_test_idx ON test(a, b) COMPRESS ADVANCED LOW local
    (PARTITION p1 COMPRESS ADVANCED LOW,
     PARTITION p2 COMPRESS,
     PARTITION p3,
 PARTITION p4 NOCOMPRESS);

7. _use_nosegment_indexes parameter and nosegment keyword:

In contrast to conventional indexes, a virtual index has no associated segment, so the creation time and associated disk space are irrelevant. In addition, it is not seen by other sessions, so it doesn't affect the normal running of your system. This article presents a simple example of how virtual indexes are used.

A virtual index is a "fake" index whose definition exists in the data dictionary, but has no index tress association.  It is used by Oracle developers to test whether a specific index is going to use useful without having to use the disk space associated with the "real" index.  The hidden parameter _use_nosegment_indexes is used by Quest tools and is also use in the Oracle Tuning pack.

Because the virtual index is a fake index, Oracle will never be able to use it, but you can use the hidden _use_nosegment_indexes parameter to evaluate execution plans for virtual indexes:

SQL> set autotrace on explain;
SQL> alter session set "_use_nosegment_indexes" = true;
Session altered.
SQL> select ename from emp where ename = 'MILLER';

ENAME
-----
MILLER

1 rows selected.

OBJECT     OPERATION
---------- ----------------------------------------
                 SELECT STATEMENT()
                  NESTED LOOPS()
EMP                TABLE ACCESS(FULL)
EMP                 TABLE ACCESS(BY INDEX ROWID)
VIRTUAL_INDEX         INDEX(UNIQUE SCAN)

Creating virtual indexes:

The CREATE INDEX statement has a special hidden "nosegment" clause that allows one to create an index definition without actually creating the index.

To build a virtual index, runs the following statement:

CREATE unique INDEX virt_ind_name on table_name(col_name) NOSEGMENT;

Removing virtual indexes:

It is important to drop the index after you're done with it.
e.g.,
DROP INDEX virt_ind_name;

8. Create Tigger with DISABLE : (Oracle 11g onwards)

Prior to Oracle 11g, disabling triggers used to be a two step process. Triggers were automatically created in an ‘enabled’ state. To disable it we had to disable it using the DISABLE clause of the ‘ALTER TRIGGER’ or ‘ALTER TABLE ‘ commands.

In Oracle 11g, we can specify ‘DISABLE’ clause in trigger definition it self.  In the absence of the ‘DISABLE’ clause, the trigger is created in an ‘ENABLED’ state. Following is the script to create table and then create trigger in disabled state.

CREATE TABLE TEST
(
COL1 VARCHAR(5) NOT NULL,
COL2 NUMBER(5),
COL3 DATE
);

Let us create a trigger now.

CREATE OR REPLACE TRIGGER TRI_TEST
BEFORE INSERT ON TEST
FOR EACH ROW
DISABLE
BEGIN
:NEW.COL3 := SYSDATE;
END;

Trigger will be created successfully.  We can verify the status of the trigger using data dictionary view user_triggers. Even though trigger is created in a disabled status,  Oracle will make sure that it does not have any compilation errors. Trigger will be compiled with errors if we try to reference non-existent column in the trigger.

This feature can be very useful when we want to enable trigger at later stage for a specific events and as mentioned earlier, we can avoid extra step of altering the trigger after creation.

9. Export direct =y ( EXPDP direct=y …)

The speedup of the direct path export can be large however. The 10% of the processing that it cuts out, accounts for a much larger percentage of the run-time. For example, I have just exported about 100meg of data, and 1.2 million records. The direct path export took about one minute. The conventional path export on the other hand took three minutes.

Setting direct=true bypasses the SGA, so it will be faster. Help full in case mission critical/ OLTPs environments.

10. SQL*Plus Error Logging

Suppose you have a SQL script called myscript.sql:

set puase on
set lines 132 pages 0 trimsppol on
select * from nonexistent_table
/

Note there are several errors in the script: the first line has "pause" misspelled, the second line has "trimspool" misspelled, and finally the third line has a select statement from a table that does not even exist. When you run the script via SQL*Plus prompt, unless you spooled the output, you will not be able to check the error afterward. Even if you spooled, you would have access to the physical server to examine the spool file, which may not be possible.

Oracle Database 11g has a perfect solution: Now you can log the errors coming from SQL*Plus on a special table. You should issue, as a first command:

SQL> set errorlogging on

Now you run the script:

SQL> @myscript

The run will produce the following error messages:

SP2-0158: unknown SET option "puase"
SP2-0158: unknown SET option "trimsppol"
select * from nonexistent_table
              *
ERROR at line 1:
ORA-00942: table or view does not exist

which you may or may not have seen, depending on how you ran the script—in the foreground from an SQL*Plus prompt or in the background as a script invocation. After the script completes, you can log into the database and check the errors in a table named SPERRORLOG.

sql> col timestamp format a15
sql> col username format a15
sql> col script format a10
sql> col identifier format a15
sql> col statement format a20
sql> col message format a20
sql> select timestamp, username, script, statement, message
  2> from sperrorlog;

Note that you checked the error from a different session, not the session where the script was run. In fact the script has finished and the session has been terminated anyway. This gives you a powerful ability to check errors after they occurred in SQL*Plus sessions that were impossible, or at least difficult, to track otherwise.

The table SPERRORLOG is a special table that is created for this purpose only. You can also create your own table and populate that with errors from SQL*Plus. This table should be created as:

SQL> create table my_sperror_log
  2  (
  3     username varchar2(256),
  4     timestamp       timestamp,
  5     script          varchar2(1024),
  6     identifier      varchar(256),
  7     message         clob,
  8     statement       clob
  9  )
 10  /

Table created.

Now you can use this table in error logging instead of the default table.

SQL> set errorlogging on table sh.my_sperror_log;
SQL> @myscript

Now MY_ERROR_LOG (and not SPERRORLOG) will hold the error log. You can truncate all the rows in the table by issuing

SQL> set errorlogging on truncate

There is an optional IDENTIFIER clause that allows you to tag the errors from specific sessions. Suppose you issue the command:

SQL> set errorlogging on identifier MYSESSION1

Now if you run the script, the records will be created with the column called IDENTIFIER populated with the value MYSESSION1. You can extract those records only by issuing the query:

select timestamp, username, script, statement, message
from sperrorlog
where identifier = 'MYSESSION1';

You will see the records from that session only. This is very useful if you are trying to isolate errors in multiple scripts and sessions.


Translate >>