Showing posts with label databases. Show all posts
Showing posts with label databases. Show all posts

Thursday, February 27, 2025

Oracle SGA vs PGA Usages and Concepts

Why Oracle Uses PGA Instead of SGA for Large Table Scans and How to Optimize It


Alireza Kamrani
02/27/2025

When selecting from large tables, Oracle might use PGA instead of SGA, depending on memory settings, query complexity, and table size. Understanding how full table scans, SGA caching, and PGA memory allocation interact can help optimize performance.

Direct path read:
The session is waiting for a direct read to complete. A direct read is a physical  I/O from a data file that bypasses the buffer cache and reads the data block directly into process-private memory.

If asynchronous I/O is supported (and in use), then Oracle can submit I/O requests and continue processing. Oracle can then pick up the results of the I/O request later and wait on "direct path read" until the required I/O completes.

If asynchronous I/O is not being used, then the I/O requests block until completed but these do not show as waits at the time the I/O is issued. The session returns later to pick up the completed I/O data but can then show a wait on "direct path read" even though this wait will return immediately.

Hence this wait event is very misleading because:

• The total number of waits does not reflect the number of I/O requests

• The total time spent in "direct path read" does not always reflect the true wait time.

This style of read request is typically used for:

• Sort I/O (when a sort does not fit in memory)

• Parallel Query slaves

• Read ahead (where a process may issue an I/O request for a block it expects to need in the near future)


Why Oracle Uses PGA Instead of SGA in Large Table Queries

1. Full Table Scans and Direct Path Reads (Bypassing SGA)

• When performing a full table scan on a very large table, Oracle may choose direct path reads, bypassing the SGA (Buffer Cache) and reading data directly into PGA.

• This happens when:

• The table is too large to fit into DB_CACHE_SIZE.

• The query requests a parallel execution plan.

• The system is under memory pressure, and Oracle determines that using PGA is more efficient than filling up SGA with temporary data.

• Result: Data is not cached in SGA, meaning future queries on the same table will not benefit from cache reuse, leading to repeated disk I/O.

2. Impact of DB_BIG_TABLE_CACHE_PERCENT_TARGET

Oracle introduced the DB_BIG_TABLE_CACHE_PERCENT_TARGET parameter to control large table caching in SGA.

• By default, large table scans use direct path reads (bypassing the SGA).

• If DB_BIG_TABLE_CACHE_PERCENT_TARGET is set, Oracle will attempt to cache full table scan results in a special area of the buffer cache, reducing repeated disk I/O.

Example Configuration:

ALTER SYSTEM SET DB_BIG_TABLE_CACHE_PERCENT_TARGET = 30;

• Effect: Reserves 30% of the buffer cache for full table scans, reducing reliance on direct path reads and keeping frequently scanned large tables in memory.


3. When PGA is Used More Than SGA

Oracle moves sorting and temporary operations to PGA instead of SGA in the following cases:

(a) Sort and Hash Joins on Large Datasets

• If a query involves sorting, aggregations, or hash joins, Oracle may store intermediate results in PGA rather than SGA.

• If the PGA_AGGREGATE_TARGET is too small, Oracle will spill temporary data to TEMP tablespace, slowing down performance.


Optimization:

ALTER SYSTEM SET PGA_AGGREGATE_TARGET = 4G;  --adjust based on your workload.

(b) Large Full Table Scans Without Proper Caching

• If DB_BIG_TABLE_CACHE_PERCENT_TARGET is not set, Oracle bypasses the buffer cache for large tables, forcing data to be processed in PGA or TEMP tablespace.

• This is inefficient for frequently accessed large tables.

Solution: Enable Large Table Caching

ALTER SYSTEM SET DB_BIG_TABLE_CACHE_PERCENT_TARGET = 25;

• Now, Oracle will try to keep large table scans in memory, avoiding repeated disk reads.

4. Should You Keep Large Tables in SGA or Let Oracle Use PGA?

• Frequently scanned large tables

Recommendation: Enable DB_BIG_TABLE_CACHE_PERCENT_TARGET.

• One-time full table scans (ad hoc queries)

Recommendation: Allow PGA direct path reads.

• Large table joins with sorting/hashing

Recommendation: Increase PGA_AGGREGATE_TARGET.

• System has low memory

Recommendation: Use direct path reads to reduce SGA pressure.

• Keeping large tables in SGA (DB_BIG_TABLE_CACHE_PERCENT_TARGET) is beneficial only if they are frequently accessed.

• For one-time scans or infrequent queries, direct path reads using PGA are better, as they prevent SGA pollution (filling cache with unnecessary data).

5. Monitoring Full Table Scan Behavior

To check if Oracle is using direct path reads (PGA) instead of SGA:

SELECT name, value FROM v$sysstat WHERE name IN ('table scans (direct read)', 'table scans (long tables)', 'physical reads direct');

• High "physical reads direct" → Indicates full table scans are bypassing the buffer cache (using PGA).

• High "table scans (long tables)" → Oracle is scanning large tables frequently.

If direct path reads are too high and performance is suffering, consider increasing DB_BIG_TABLE_CACHE_PERCENT_TARGET.

Conclusion

• Oracle uses PGA instead of SGA for large table scans when full table scans are performed via direct path reads.
• Setting DB_BIG_TABLE_CACHE_PERCENT_TARGET helps keep frequently accessed large tables in memory to avoid repeated I/O.
• For queries involving sorting, hashing, or aggregations, PGA tuning is critical (PGA_AGGREGATE_TARGET should be increased to prevent excessive disk usage).
• Use SGA for frequently accessed tables and PGA for complex sorting and temporary operations.

Alireza Kamrani, Database Consultant/ACE

Tuesday, February 18, 2025

An Overview of Oracle database buffer cache behavior and keep blocks into memory solutions

An Overview of Oracle database buffer cache behavior and keep blocks into memory solutions.


Alireza Kamrani

18 Feb 2025

We can run some commands to cache  table blocks in Oracle buffer cache, but is there any guarantee to keep all blocks of mentioned table in buffer cache anytime?

In Oracle , if you want a table to always be cached in memory to improve performance, you can use the KEEP buffer pool or the Result Cache. However, BUFFER CACHE in the ALTER TABLE command is primarily a hint for caching table blocks in the default buffer cache.

Options to Keep a Table in Memory:

1. Using the KEEP Buffer Pool

Oracle allows you to keep frequently accessed tables in the KEEP buffer pool to avoid them being aged out of memory.

• Enable the KEEP pool in your SGA:

ALTER SYSTEM SET DB_KEEP_CACHE_SIZE = nG;

n: adjust it based on you memory.

• Assign the table to the KEEP pool:

ALTER TABLE my_table STORAGE (BUFFER_POOL KEEP);

Or also:

ALTER TABLE my_tabl CACHE;

2. Using the BUFFER CACHE Clause

You can specify that table blocks should be kept in the buffer cache:

ALTER TABLE my_table STORAGE (BUFFER CACHE);

• This helps in keeping the table’s data in the buffer cache for longer.

• Useful for small lookup tables that are frequently accessed.

3. Using the Result Cache (For Query Caching)

If the table is frequently queried and doesn't change often, you can enable query result caching:

ALTER TABLE my_table RESULT_CACHE (MODE FORCE);

• This keeps the query results in the Result Cache rather than just buffering the table blocks.


Which One Should You Use?

• Use KEEP Buffer Pool for frequently accessed small tables that should always stay in memory.

• Use BUFFER CACHE for tables where you want their data blocks to stay in the buffer cache longer.

• Use RESULT CACHE if the queries on the table return the same results frequently and the table doesn't change often.


Is there any solution to guarantee keeping all table blocks residents into memory?

No, Oracle does not force a full cache and guarantee that all blocks of a database will remain in memory.
After any of above solution about caching of a sample table in buffer , Oracle does not do anything immediately, and your command done easily!
So, running any mentioned solutions does not keeping blocks as soon as possible, when Oracle try to change your priorities about this table to keep in cache but these is not any guarantee about that and that is very dependent on pressure on memory and workloads.

While Oracle uses a sophisticated caching mechanism, the database will not guarantee that all blocks will stay in memory at all times. Oracle uses the System Global Area (SGA) and the Buffer Cache to cache frequently accessed data blocks, but the caching behavior is influenced by various factors, such as:

• Memory Availability: The SGA has a limited amount of memory, and the database will keep as many blocks in memory as possible, but once it exceeds its capacity, older or less frequently used blocks will be flushed to disk.

• Database Cache Management: Oracle dynamically manages the buffer cache to balance memory between different cache types (like the Database Buffer Cache, Shared Pool, etc.), based on usage patterns.

• LRU (Least Recently Used) Algorithm: Blocks that are not frequently accessed are more likely to be replaced by other blocks. This means that not all blocks are guaranteed to remain in memory.


• Memory Parameters: Settings like DB_CACHE_SIZE and PGA_AGGREGATE_TARGET determine how much memory is allocated to caching. However, the actual memory used can fluctuate based on system activity and load.

• Large Tables or Objects: Very large objects or tables might not fit entirely in memory, and Oracle will load and evict blocks based on access patterns.

In summary, Oracle will try to keep as much data in memory as it can based on available resources and usage patterns, but it does not guarantee that all blocks will remain cached in memory all the time.


What is usage of Force Full Caching mechanism?

If you are using the ALTER DATABASE FORCE FULL DATABASE CACHING command, the behavior changes slightly.

When you run this command, Oracle will indeed attempt to keep all data blocks in memory. Specifically:

• Force Full Database Caching: This command forces Oracle to cache all database blocks for tables and indexes into memory (specifically into the Database Buffer Cache). This means that Oracle will attempt to keep all blocks that are accessed in memory, regardless of the usual cache replacement mechanisms.

However, there are still some important nuances to understand:

• Memory Constraints: While Oracle will attempt to cache all blocks, it doesn't mean the entire database will fit into memory if the available memory is not enough. If the system doesn't have enough memory to store every block, the database will still perform evictions based on available resources. This command doesn't increase physical memory; it just prioritizes caching.

• Increased Memory Usage: This command will increase memory consumption because the cache size will grow, and more memory will be allocated to caching the blocks. You need to have sufficient memory for this to be effective.

• Specific to Tables and Indexes: This command will affect all user tables and indexes. It does not automatically apply to other structures like the redo log buffer or shared pool, which will still be managed according to normal memory rules.


• System Behavior: Even with the FORCE FULL DATABASE CACHING command, blocks are still subject to eviction when there are memory pressures, but the priority of eviction is adjusted. Oracle will avoid evicting blocks from the cache unless absolutely necessary.

In summary:

Yes, using ALTER DATABASE FORCE FULL DATABASE CACHING will attempt to keep all database blocks in memory, but it's still dependent on available system memory. It doesn't guarantee that all blocks will always stay in memory if there are memory limitations or if the system faces memory pressure, but Oracle will prioritize caching them more aggressively compared to the default behavior.


Alireza Kamrani.

Saturday, December 14, 2024

Overview of DBMS_FS package To Managing File Systems into Oracle

 Overview of DBMS_FS package :

The DBMS_FS package for performing operations on an Oracle file system (make, mount, unmount and destroy operations) in an Oracle database.


              Alireza Kamrani 

                12/14/2024


This chapter contains the following topics:

  • DBMS_FS Overview
  • DBMS_FS Security Model
  • Summary of DBMS_FS Subprograms


DBMS_FS Overview

The DBMS_FS package contains Oracle file system (OFS) procedures that you can use to create, mount, unmount, and destroy an Oracle file system.

Starting 19c release, the file systems are supported by PDB. 


Oracle Database supports maximum 5 file systems per PDB and 1000 file systems in total.


The DBMS_FS package enables applications to access database objects from a universal client such as an NFS server. 

This feature interfaces with Oracle SecureFiles to provide the file system access. 


DBMS_FS Security Model

You must have the SYSDBA administrative privilege to use the DBMS_FS package. 

The operations that you perform using the DBMS_FS package are equivalent to the file system operations that are performed in an operating system by the root user. 


Access to the individual file system that is created and mounted by this package is enforced using Access Control Lists (ACLs) and the permissions on the mounted directories to the operating system user.


Example:

The following sample code shows how to check if a file system exists with the specified file system name, data.


SQL> declare

     fsname varchar2(64) := 'data';

     fsexists integer;

     

 begin

 fs_exists := dbms_fs.fs_exists(fsname);

 dbms_output.put_line('fs exists: ' || fsexists);

 end;

     /


SQL> select dbms_fs.fs_exists('data') from dual; 


The following sample code shows how to list all the files within a specified directory in a file system.


SQL> select * from DBMS_FS.LIST_FILES ('data', '/') from dual;


Where, the path to the directory ('/') is relative to the mount path.


Usage Notes:

If you want to create a database file system (DBFS), then you must run the dbfs_create_filesystem.sql script, which in turn calls the dbfs_create_filesystem_advanced.sql script. 

By default, this script is in the $ORACLE_HOME/rdbms/admindirectory. 


When you run this script, provide the name of an existing tablespace and a name for the file system that will be stored in the database. The size of the file system will be the same as the table size.


For example, to create a file system in the dbfs_ts tablespace, in the file system dbfs_tab:

@/$ORACLE_HOME/rdbms/admin/dbfs_create_filesystem.sql dbfs_ts dbfs_tab

After you run this script, you can use the other procedures in the DBMS_FS package to mount, unmount, and destroy the file system. 

Note:

Staring Oracle Database 19.3.1.0 release, the DBMS_FS.MAKE_ORACLE_FS is used to create a DBFS filesystem; hence no auxiliary SQL script is needed to create a DBFS filesystem.


Running the DBMS_FS.MAKE_ORACLE_FS procedure on the database instance is equivalent to running the mkfs command by root in an operating system. 


The tablespace that you specified in the fsoptions parameter must already exist before you execute the DBMS_FS.MAKE_ORACLE_FS procedure. 

To find existing tablespaces, query the DBA_TABLESPACES data dictionary view.


The size of the file system is the same size as this tablespace. 


Example:

The following example shows how to create a DBFS file system named dbfs_fs1 in the tablespace dbfs_fs1_tbspc.


BEGIN

 DBMS_FS.MAKE_ORACLE_FS (

  fstype           => 'dbfs',

  fsname           => 'dbfs_fs1',

  fsoptions        => 'TABLESPACE=dbfs_fs1_tbspc');

END;

/


MOUNT_ORACLE_FS Procedure

Use the dbms_fs.mount_oracle_fs() procedure to mount an Oracle file system or OFS managed file system on the specified mount point.

Before you begin, complete the following checks to ensure that:

  • You have created the file system using the dbms_fs.make_oracle_fs()procedure.
  • The mount point that you specify exists in the local node.
  • The Oracle user has access permissions.
  • The mount path is empty, which means that the directory specified by the mount point does not have any files.

Oracle supports an extensive list of mount options that you can use to have better control on resources and achieve good performance. When you use the persist mount option, file systems are automatically remounted every time instance restarts. 


Since OFSD is a non-fatal background process, it gets automatically restarted after the death of a process. 

File systems that are mounted at the time of the death of the OFSD process are automatically remounted after starting a new OFSD process. 


This ensures continuous availability of the mounted file systems even in the case of an error.


To improve the throughput, OFSD has its own local cache for writes and reads. 


The write cache uses 8 (1 MB) buffers per file connection, and it can use up to 256 MB per file system. 

You can modify this value through the mount option, wcache_size. 


A read-ahead algorithm is implemented for read operation and it uses 2 (1 MB) per file connection and it can use up to 256 MB per file system. Use the mount option, rcache_size, to modify this value. 


The read-write cache is maintained per node, so this provides local cache consistency. 


In an RAC environment, consistency is guaranteed only after the flush() or close() operation is performed on the file. 


When two different processes on two different RAC nodes modify a single file and write to the same offset, then the first process that performs the close() operation on the file will have its data written into the file. 


Syntax:


Mounts a DBFS file system

Mounts a DBFS file system at /oracle/dbfs/testfs.


BEGIN

 DBMS_FS.MOUNT_ORACLE_FS (

  fstype           => 'dbfs',                              

  fsname           => 'dbfs_fs1',                              

  mount_point      => '/oracle/dbfs/testfs',                              

  mount_options    => 'default_permissions, allow_other, db_access'); 

END;


Example: 

Persist mount a DBFS file system

Persist mounts a DBFS file system at /oracle/dbfs/testfs.


BEGIN

 DBMS_FS.MOUNT_ORACLE_FS (

  fstype           => 'dbfs',                              

  fsname           => 'dbfs_fs1',                              

  mount_point      => '/oracle/dbfs/testfs',                              

  mount_options    => 'default_permissions, allow_other, persist, db_access'); 

END;


UNMOUNT_ORACLE_FS Procedure

This procedure unmounts an Oracle file system on the specified mount point. 

File systems that are mounted in a PDB are automatically unmounted when the PDB is closed. 


You can also use dbms_fs.unmount_oracle_fs() to explicitly unmount an Oracle file system that you have mounted through OFS.


Usage Notes:

  • Before you unmount the file system, ensure that all applications that use this file system are shut down. Also ensure that no processes reference the mounting file system.
  • You can find information about the currently mounted file systems by querying the V$OFSMOUNT dynamic view.
  • After unmounting the file system, the write permissions are removed from the mount point to prevent applications from writing to the underlying file system instead of the OFS supported file systems.
  • When an Oracle instance is shut down in normal immediate mode, then all the mounted file systems are automatically unmounted.
  • If a file system is mounted with the MOUNT_ORACLE_FS procedure with the persist option, it will be automatically mounted again when the database instance starts or the PDB is plugged. If this file system is unmounted by executing DBMS_FS.UNMOUNT_ORACLE_FS, it will remain unmounted even if the persistoption was used to mount it.
  • If you perform a SHUTDOWN ABORT, then the file system may still show as mounted but it may not be accessible. In this case, you can unmount the system manually by calling the unmountcommand at the operating system level or the fusermount procedure on Linux systems.
  • Do not use fusermount -u to unmount a running file system as it causes inconsistency in Oracle views, such as v$ofsmount.
  • You can export the local mount point of an Oracle file system to point to the remote system, and then NFS mount the file system from the remote system by using the operating system mountcommand. The DBMS_FS.MOUNT_ORACLE_FS procedure is similar to mount commands that are used for other local file systems.
  • For better security, Oracle recommends that you use access control lists (ACLs) and Kerberos to control access to sensitive data.
  • Do not attempt to unmount the file system from the operating system level. Doing so can leave the Oracle Database-created file system internal tables in an inconsistent state.


Example:

The following sample code unmounts a DBFS mounted file system at /oracle/dbfs/testfs.


BEGIN

 DBMS_FS.UNMOUNT_ORACLE_FS (

  fsname           => 'dbfs_fs1',                              

  mount_point      => '/oracle/dbfs/testfs',

  mount_options    => 'force'); 

END;

IMG_7957.jpeg

Alireza Kamrani 

Oracle Database Performance: Avoiding Unnecessary Table Scans

Oracle Database Performance: Avoiding Unnecessary Table Scans One of the common recommendations in database performance tuning is to avoid...