Wednesday, September 4, 2024

Oracle EXPDP commands

The expdp (Data Pump Export) utility is used to export data and metadata from an Oracle database. It provides several command-line options to customize the export process. Below are some common expdp commands and their explanations:


Basic Syntax:

 


expdp [username/password] DIRECTORY=directory_name DUMPFILE=dumpfile_name LOGFILE=logfile_name [options]


Common Expdp Commands:

    • Export a Full Database:

expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=full_db.dmp LOGFILE=full_db.log

    • FULL=Y: Exports the entire database.
    • Export a Specific Schema:

expdp system/password SCHEMAS=schema_name DIRECTORY=dpump_dir DUMPFILE=schema.dmp LOGFILE=schema.log
    • SCHEMAS=schema_name: Exports a specific schema.
    • Export Specific Tables:

expdp system/password TABLES=table1,table2 DIRECTORY=dpump_dir DUMPFILE=tables.dmp LOGFILE=tables.log
    • TABLES=table1,table2: Exports specific tables.
    • Export a Specific Table with Data and Metadata:

expdp system/password TABLES=table_name DIRECTORY=dpump_dir DUMPFILE=table.dmp LOGFILE=table.log
    • TABLES=table_name: Exports a specific table.
    • Export with Compression:

expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=full_db.dmp LOGFILE=full_db.log COMPRESSION=ALL
    • COMPRESSION=ALL: Compresses all data during export.
    • Export with Data Filtering (e.g., Export Data from a Specific Date):

expdp system/password TABLES=table_name DIRECTORY=dpump_dir DUMPFILE=table.dmp LOGFILE=table.log QUERY=table_name:"WHERE created_date > TO_DATE('2024-01-01', 'YYYY-MM-DD')"
    • QUERY=table_name:"WHERE condition": Filters rows based on a condition.
    • Export Metadata Only:
    • expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=metadata.dmp LOGFILE=metadata.log CONTENT=METADATA_ONLY
    • CONTENT=METADATA_ONLY: Exports only metadata (no data).
    • Export Data Only:

expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=data_only.dmp LOGFILE=data_only.log CONTENT=DATA_ONLY
    • CONTENT=DATA_ONLY: Exports only data (no metadata).
    • Export a Database with a Specific Date Format:

expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=full_db.dmp LOGFILE=full_db.log PARALLEL=4
    • PARALLEL=4: Uses 4 parallel threads for faster export.
  • Export with a Job Name:


expdp system/password FULL=Y DIRECTORY=dpump_dir DUMPFILE=full_db.dmp LOGFILE=full_db.log JOB_NAME=export_full_db
    • JOB_NAME=export_full_db: Assigns a name to the export job.


Additional Parameters:

  • CONTENT: Specifies whether to export metadata only (METADATA_ONLY), data only (DATA_ONLY), or both (ALL).
  • EXCLUDE: Excludes specific objects or object types from the export. Example: EXCLUDE=TABLE:"='table_name'".
  • INCLUDE: Includes specific objects or object types in the export. Example: INCLUDE=TABLE:"IN ('table1', 'table2')".
  • REMAP_SCHEMA: Remaps schema names. Example: REMAP_SCHEMA=old_schema:new_schema.
  • REMAP_TABLESPACE: Remaps tablespace names. Example: REMAP_TABLESPACE=old_tablespace:new_tablespace.


Directory Object:

Before running expdp, ensure that the DIRECTORY object exists in the database and points to a valid filesystem directory where the dump files will be written.

 

 

CREATE OR REPLACE DIRECTORY dpump_dir AS '/path/to/directory';


Example Execution:

To execute an expdp command, open a command prompt or terminal and run the appropriate expdp command based on your requirements. Ensure you have the necessary privileges and that the Oracle environment variables (ORACLE_HOME and PATH) are set correctly.



Conclusion:

The expdp utility offers powerful options for exporting data and metadata from Oracle databases. By using the appropriate parameters and options, you can tailor the export process to meet specific needs and optimize performance.

Monday, August 19, 2024

Identify and Terminate Sessions in oracle

 

First, you have to identify the session to be killed with alter system kill session.

Step-by-Step Instructions to Identify and Terminate a Session:


Invoke SQL*Plus:

First, open SQL*Plus to begin the process.

Query V$SESSION to Identify the Session:

Use the following query to retrieve the session details. This will list all active sessions with their respective SID, SERIAL#, STATUS, SCHEMANAME, and PROGRAM.


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session;

The SID (Session Identifier) and SERIAL# values of the Oracle session to be killed can then be identified from this output.


Execute the ALTER SYSTEM Command:

Substitute the identified SID and SERIAL# values and issue the alter system kill session command.


ALTER SYSTEM KILL SESSION 'sid,serial#';

Handling Sessions Marked for Kill:

Sometimes, Oracle is not able to kill the session immediately with the alter system kill session command alone. Upon issuing the command, the session may be 'marked for kill' and will be terminated as soon as possible.


Forcing Session Termination:

In the case where a session is 'marked for kill' and not terminated immediately, you can force the termination by adding the immediate keyword:


ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

Verify Termination:

To ensure that the session has been terminated, re-query the V$SESSION dynamic performance view:


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session WHERE SID = 'sid' AND SERIAL# = 'serial#';

The value of the STATUS column will be 'ACTIVE' when the session is making a SQL call and 'INACTIVE' if it is not.


Confirm PMON Cleanup:

After the Process Monitor (PMON) has cleaned up the session, the row will be removed from V$SESSION. Re-query to confirm:


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session WHERE SID = 'sid' AND SERIAL# = 'serial#';

Handling RAC Environments:

In a Real Application Clusters (RAC) environment, you can optionally specify the INST_ID, which is shown when querying the GV$SESSION view. This allows you to kill a session on a different RAC node.


ALTER SYSTEM KILL SESSION 'sid,serial#,@inst_id';

By following these detailed steps, you can efficiently identify and terminate a session using SQL*Plus, ensuring minimal disruption and maintaining database integrity.

Friday, September 13, 2019

import a single table from a full export backup in oracle


import a single table from a full export backup and remap it


impdp USERNAME/PASSWORD tables=SCHEMA.TABLE_NAME directory=DPUMP dumpfile=DUMPFILE_%U.dmp
remap_schema=SOURCE:TARGET 
REMAP_TABLE=TABLE_NAME:TABLE_NAME_NEW


Optional things above :

  1. Remove remap if you don't want.
  2. Add ENCRYPTION_PASSWORD=IF_ANY

Friday, February 2, 2018

Restoring archive logs from an RMAN backup

Restoring archive logs from an RMAN backup is a common task when you need to recover database transactions to a specific point in time. The commands you've provided are examples of how to restore archive logs using RMAN (Recovery Manager). Below are explanations of each command:

1. Using RESTORE ARCHIVELOG FROM LOGSEQ ... UNTIL LOGSEQ ... THREAD

sql

RMAN> RESTORE ARCHIVELOG FROM LOGSEQ=37501 UNTIL LOGSEQ=37798 THREAD=1;
  • Purpose: This command restores archive logs from the RMAN backup, specifically those logs that fall between the log sequence numbers 37501 and 37798 for the specified thread (in this case, thread 1).

  • Parameters:

    • FROM LOGSEQ=37501: Specifies the starting sequence number of the archive logs you want to restore.
    • UNTIL LOGSEQ=37798: Specifies the ending sequence number of the archive logs to restore.
    • THREAD=1: Indicates the thread number (useful in RAC environments where there are multiple redo threads).
  • Use Case: This approach is ideal when you know the exact range of log sequences you need to restore and want to limit the restoration to a specific thread.

2. Using RESTORE ARCHIVELOG BETWEEN SEQUENCE ... AND ...

sql

RMAN> RESTORE ARCHIVELOG BETWEEN SEQUENCE 37501 AND 37798;
  • Purpose: This command restores all archive logs between the specified sequence numbers (37501 to 37798) from all threads unless a specific thread is specified elsewhere.

  • Parameters:

    • BETWEEN SEQUENCE 37501 AND 37798: Specifies the range of archive log sequences you want to restore.
  • Use Case: This command is useful when you want to restore a continuous range of archive logs across all threads without specifying individual thread numbers.

Key Points:

  • Ensure that the archive logs you are restoring are available in your RMAN backup.
  • These commands do not apply the restored archive logs; they only restore them to the specified location (usually the archive log destination).
  • Check the current location and status of the logs using RMAN commands such as LIST BACKUP OF ARCHIVELOG before performing the restore operation.
  • It's critical to be cautious with thread specification, especially in RAC environments, to avoid restoring unnecessary logs or missing required logs.

These commands are powerful tools for managing archive log restoration and can help ensure that you have the necessary logs for database recovery or point-in-time recovery operations.

Monday, October 16, 2017

set up the OPatch environment variable for Oracle Patching

To set up the OPatch environment variable, you need to add the OPatch directory (located within your Oracle Home) to your system’s PATH variable. This allows you to run OPatch commands directly from any shell prompt without specifying the full path. Below are the steps for setting up the PATH environment variable for both Korn/Bourne shells (like sh, bash, ksh) and C Shell (csh, tcsh).

Setting Up OPatch Environment Variable

  1. For Korn Shell (ksh), Bourne Shell (sh), and Bash Shell:

    Use the export command to modify the PATH variable.

    sh:

    # Add OPatch to the PATH export PATH=$PATH:$ORACLE_HOME/OPatch
    • Explanation:
      • export PATH=$PATH:$ORACLE_HOME/OPatch: This command appends the OPatch directory to the current PATH variable, making the OPatch utility accessible from the command line.
      • $ORACLE_HOME/OPatch: Refers to the OPatch directory within the Oracle Home path.
  2. For C Shell (csh, tcsh):

    Use the setenv command to update the PATH variable.

    csh:

    # Add OPatch to the PATH setenv PATH $PATH:$ORACLE_HOME/OPatch
    • Explanation:
      • setenv PATH $PATH:$ORACLE_HOME/OPatch: This command updates the PATH variable by appending the OPatch directory, allowing OPatch commands to be run without specifying the full path.

Important Notes:

  • Ensure Oracle Home is Set: Before running these commands, make sure the ORACLE_HOME environment variable is correctly set to your Oracle installation path. You can verify it using echo $ORACLE_HOME.
  • Persistent Changes: To make these changes persistent across sessions, add the corresponding command to your shell’s startup file (~/.bash_profile, ~/.profile for Bash/Korn shell or ~/.cshrc for C shell).
  • Verify OPatch: After setting the variable, verify the setup by running opatch version to ensure that the command is accessible and the correct OPatch version is in use.

This setup is crucial for applying patches and managing updates in your Oracle environment effectively using OPatch

Tuesday, September 12, 2017

Simple Oracle Plsql Package for password encryption and decryption

The script you provided demonstrates how to create a simple password encryption and decryption package in Oracle using the DBMS_OBFUSCATION_TOOLKIT. Below is a step-by-step breakdown of each part of the code:

1. Setting Up the Environment:

Before running the package, it is recommended to connect to the database as SYSDBA and run the script ?/rdbms/admin/catobtk.sql. This script installs the DBMS_OBFUSCATION_TOOLKIT package, which is necessary for encryption and decryption functionalities.

2. Creating the Table USERS_INFO:

The table USERS_INFO is created to store usernames and encrypted passwords.



CREATE TABLE USERS_INFO
(
  USERNAME VARCHAR2(20 BYTE),
  PASS VARCHAR2(20 BYTE)
);


3. Creating the Package Specification PASSWORD:

The package specification defines two functions: encrypt and decrypt. These functions will handle the encryption and decryption of passwords.


CREATE OR REPLACE PACKAGE PASSWORD AS
   function encrypt(i_password varchar2) return varchar2;
   function decrypt(i_password varchar2) return varchar2;
END PASSWORD;
/
show errors

4. Creating the Package Body PASSWORD:

The package body implements the actual logic for the encrypt and decrypt functions using Oracle's DBMS_OBFUSCATION_TOOLKIT.

Key Points:

  • The encryption key (c_encrypt_key) must be exactly 8 bytes long.
  • Input data for encryption must have a length divisible by eight, achieved using RPAD to pad the input string.

CREATE OR REPLACE PACKAGE BODY PASSWORD AS

  -- Key for encryption and decryption
  c_encrypt_key VARCHAR2(8) := 'key45678';

  -- Encrypt function
  FUNCTION encrypt (i_password VARCHAR2) RETURN VARCHAR2 IS
    v_encrypted_val VARCHAR2(38);
    v_data          VARCHAR2(38);
  BEGIN
     -- Pad the input data to a length divisible by eight
     v_data := RPAD(i_password, (TRUNC(LENGTH(i_password)/8) + 1) * 8, CHR(0));

     -- Encrypt the data
     DBMS_OBFUSCATION_TOOLKIT.DESENCRYPT(
        input_string     => v_data,
        key_string       => c_encrypt_key,
        encrypted_string => v_encrypted_val);
     RETURN v_encrypted_val;
  END encrypt;

  -- Decrypt function
  FUNCTION decrypt (i_password VARCHAR2) RETURN VARCHAR2 IS
    v_decrypted_val VARCHAR2(38);
  BEGIN
     -- Decrypt the data
     DBMS_OBFUSCATION_TOOLKIT.DESDECRYPT(
        input_string     => i_password,
        key_string       => c_encrypt_key,
        decrypted_string => v_decrypted_val);
     RETURN v_decrypted_val;
  END decrypt;

END PASSWORD;
/
SHOW ERRORS;


5. Testing the Encryption and Decryption:

The following SQL statements test the encryption and decryption functions:


select password.encrypt('PASSWORD1') from dual;
select password.decrypt(app_password.encrypt('PASSWORD1')) from dual;
select password.encrypt('PSW2') from dual;
select password.decrypt(app_password.encrypt('PSW2')) from dual;

6. Inserting and Retrieving Encrypted Data:

The script demonstrates inserting an encrypted password into the USERS_INFO table and then retrieving and decrypting it.

--- Insert encrypted Password ---

insert into USERS_INFO values ('redddy',( select password.encrypt('REDDY1') from dual) );
select password.decrypt((pass)) from USERS_INFO where USERNAME='redddy';



Important Notes:

  • Security Considerations: The DBMS_OBFUSCATION_TOOLKIT uses DES encryption, which is considered outdated and insecure by modern standards. It’s recommended to use DBMS_CRYPTO for more robust encryption methods, such as AES.
  • Error Handling: The script should include error handling to manage issues that may arise during encryption or decryption processes.
  • Testing and Validation: Always test encryption and decryption thoroughly, especially when dealing with sensitive data like passwords, to ensure the correct implementation.

This setup serves as a demonstration of basic encryption and decryption using Oracle's built-in toolkit, providing a foundation for enhancing database security.

Friday, July 14, 2017

update rows from multiple tables (correlated update)


Cross table update (also known as correlated update, or multiple table update) in Oracle uses non-standard SQL syntax format (non ANSI standard) to update rows in another table. The differences in syntax are quite dramatic compared to other database systems like MS SQL Server or MySQL.
In this article, we are going to look at four scenarios for Oracle cross table update.

Suppose we have two tables Categories and Categories_Test. See screenshots below.

lets take two tables TABA & TABB:

Records in TABA:















Records in TABB:













1. Update data in a column LNAME in table A to be upadted with values from common column LNAME in table B.

The update query below shows that the PICTURE column LNAME is updated by looking up the same ID value in ID column in table TABA and TABB.

 update TABA A
set (a.LNAME) = (select B.LNAME FROM TABB B where A.ID=B.ID);















2. Update data in two columns in table A based on a common column in table B.

If you need to update multiple columns simultaneously, use comma to separate each column after the SET keyword.

update TABA A
set (a.LNAME, a.SAL) = (select B.LNAME, B.SAL FROM TABB B where A.ID=B.ID);



Friday, June 2, 2017

How Secure Can We Make Our Oracle Databases?


How Secure Can We Make Our Oracle Databases?

As a database administrator, one of the most critical questions that constantly arises is: How secure are our databases, and can we make them any more secure? Ensuring the security of your Oracle databases is crucial, as they are often the backbone of an organization’s data infrastructure. Over the years, I’ve adopted several best practices to enhance database security. Below, I share some key tips and strategies that I follow to secure my databases:

  1. Grant Access on a Need-to-Know Basis

Always follow the principle of least privilege by granting access only to users who genuinely need it. This minimizes exposure and reduces the risk of unauthorized actions within the database.

    2. Remove Unnecessary Grants and Privileges

Regularly review and clean up unnecessary permissions from users and roles. Privileges that are no longer needed should be revoked to prevent misuse or accidental data exposure.

    3. Audit Failed Logins Regularly

Implement frequent audits of Failed Logins attempts to detect unauthorized access attempts. Monitoring failed logins helps identify suspicious activities and potential security threats. 

    4. Evaluate Requests for Elevated Privileges

When a user requests elevated privileges, always engage in a conversation to understand their requirements. Assess if the elevated access is genuinely necessary and grant it only if justified.

    5. Grant the Minimum Required Access

Ensure that users are granted no more access than what is absolutely necessary for their tasks. Avoid giving broad permissions, as this increases the risk of accidental or malicious actions.

    6. Manage Temporary Access Carefully

Sometimes, users need access temporarily for specific tasks. Make sure to track and revoke these temporary permissions immediately after the task is completed to maintain security.

    7. Define Clear Boundaries for Data Access

Clearly define which users can access specific data. Implement fine-grained access control to restrict access to sensitive data based on roles and responsibilities.

    8. Use User Profiles and Audit Features

Leverage Oracle’s User profiles & Audit capabilities to monitor and enforce security policies. Track all user activities to ensure accountability and detect any unauthorized actions. 

    9. Enforce Complex Password Policies

Implement strong password policies that require complexity and regular changes. Complex passwords significantly enhance security by making unauthorized access more difficult. Here is the Link on how to do it 

    10. Use Triggers to Track User Activity

Utilize database triggers to monitor user actions such as logins, DML operations, and changes to critical tables. This helps in tracking user behavior and detecting anomalies. Use Triggers to track user activity.

    11. Encrypt Passwords in Applications

Ensure that passwords used in applications are encrypted. Storing plain-text passwords poses a significant security threat, especially if application code is compromised.

    12. Secure the Oracle Listener with a Password

Protect your Oracle Listener with a password to prevent unauthorized access and control over database connections. This adds an additional layer of security to your database environment.

    13.  Restrict Access to Known Servers and Clients

Use Oracle’s VALID_NODE_CHECKING feature to restrict database access to specific, known servers or clients. This helps protect your database from unauthorized network access. Use this Valid_node_checking Link on how to restrict access to servers/clients.

Conclusion

Securing your Oracle databases is an ongoing process that requires continuous vigilance, regular audits, and updates to security protocols. By implementing these best practices, you can significantly enhance the security of your Oracle environments and protect your data from unauthorized access and potential threats. Remember, security is not a one-time setup but a continuous practice that evolves with emerging threats and changes in your database infrastructure.