How to Enable PL/SQL Query Logging?
Last Updated :
23 Jul, 2025
In database management, tracking and analyzing SQL queries are essential for optimizing performance, debugging issues, and ensuring efficient resource utilization. PL/SQL query logging provided a robust mechanism to capture and store the information about the SQL queries executed within the PL/SQL code. By logging the above queries developers and administrators of the database gain valuable insights into the behavior of the applications of the database.
This article explains the concept of PL/SQL query logging and provides step-by-step guidance on enabling it in an Oracle database environment. It outlines the main component involved in setting up the query logging, including the creation of the logging tables and implementation of the logger procedures or packages and instrumentation of the PL/SQL code to the logging mechanism.
Prerequisites
The following are the prerequisites to enable PL/SQL query logging:
- Access Permissions
- Database Schema
- Understanding of PL/SQL
- Database Connectivity
- Logging Strategy
Example for Enabling PL/SQL Query Logging
Step 1: Create a Logging Table
CREATE TABLE query_log (
log_id NUMBER PRIMARY KEY,
timestamp TIMESTAMP,
sql_text VARCHAR2(4000),
bind_variables VARCHAR2(4000)
);
- The above table can store the logged information, which includes the timestamp, SQL text, and bind variables.
Step 2: Write Logger Procedure or Package
CREATE OR REPLACE PACKAGE query_logger AS
PROCEDURE log_query(p_sql_text IN VARCHAR2, p_bind_variables IN VARCHAR2 DEFAULT NULL);
END query_logger;
/
CREATE OR REPLACE PACKAGE BODY query_logger AS
PROCEDURE log_query(p_sql_text IN VARCHAR2, p_bind_variables IN VARCHAR2 DEFAULT NULL) AS
BEGIN
INSERT INTO query_log (log_id, timestamp, sql_text, bind_variables)
VALUES (query_log_seq.NEXTVAL, SYSTIMESTAMP, p_sql_text, p_bind_variables);
COMMIT;
END log_query;
END query logger;
/
- This is created by the package which is named query_logger with the procedure of log_query that inserts the new record into the table of query_log.
Step 3: Instrument Your PL/SQL Code
DECLARE
v_sql_text VARCHAR2(4000);
v_bind_variables VARCHAR2(4000);
BEGIN
-- Your SQL statement
v_sql_text := 'SELECT * FROM your_table WHERE column_name = :1';
-- Bind variables (if any)
v_bind_variables := 'value_of_bind_variable';
-- Execute SQL statement
query_logger.log_query(v_sql_text, v_bind_variables);
-- Execute your SQL statement here
-- ...
END;
/
- In the above example, to log the SQL text and bind variables, you can call the log_query procedure before executing the SQL statement.
Step 4: Enabled Logging in Production
-- Ensure that logging is enabled only in non-production environments or controlled circumstances in production.
- Make sure that the logging is enabled in non-production environments or controlled circumstances in production, it may impact performance due to the additional database operations.
Step 5: Combine the Code
- Let's combine all together with the complete example
CREATE TABLE query_log (
log_id NUMBER PRIMARY KEY,
timestamp TIMESTAMP,
sql_text VARCHAR2(4000),
bind_variables VARCHAR2(4000)
);
CREATE SEQUENCE query_log_seq;
CREATE OR REPLACE PACKAGE query_logger AS
PROCEDURE log_query(p_sql_text IN VARCHAR2, p_bind_variables IN VARCHAR2 DEFAULT NULL);
END query_logger;
/
CREATE OR REPLACE PACKAGE BODY query_logger AS
PROCEDURE log_query(p_sql_text IN VARCHAR2, p_bind_variables IN VARCHAR2 DEFAULT NULL) AS
BEGIN
INSERT INTO query_log (log_id, timestamp, sql_text, bind_variables)
VALUES (query_log_seq.NEXTVAL, SYSTIMESTAMP, p_sql_text, p_bind_variables);
COMMIT;
END log_query;
END query_logger;
/
DECLARE
v_sql_text VARCHAR2(4000);
v_bind_variables VARCHAR2(4000);
BEGIN
-- Your SQL statement
v_sql_text := 'SELECT * FROM employees WHERE department_id = :1';
-- Bind variables (if any)
v_bind_variables := '20';
-- Execute SQL statement
query_logger.log_query(v_sql_text, v_bind_variables);
-- Execute your SQL statement here
-- ...
END;
/
Explanation:
- Creation of Table: The code creates the table and is named query_log to store the information about the logged SQL queries.
- Sequence Creation: It is used to create the sequence called query_log_seq to generate the unique IDs for log entries.
- Package Creation: The package is named query_logger for creating the group procedures. It contains the procedure log_query to the log SQL queries.
- Procedure Implementation: Within the package body, the log_query procedure inserts the new log entry into the query_log table, and it includes the SQL text and bind variables.
- PL/SQL Block: The DECLARE block will initialize the SQL text and bind variables. The log_query procedure is called the log SQL query into the query_log table.
Step 6: To view the data
SELECT * FROM query_log;
- This query is used to retrieve all records from the query_log table. This table shows the log IDs, execution timestamp, SQL text and bind variables of the logged queries.
Output:
OutputConclusion
In conclusion, the above code establishes a robust mechanism for logging SQL queries executed within the PL/SQL code in an Oracle database. By creating the logging table, sequence, and package, developers can effectively store valuable information about the query executions. The logging mechanism into the database applications, developers, and database administrators gain insights into the query performance, adding in debugging, optimizing, and overall monitoring of the system.
Similar Reads
PL/SQL Tutorial Explore this PL/SQL tutorial to effortlessly learn PL/SQL â It is perfect for beginners and experienced ones. Whether you're new to it or diving deep, this interactive guide simplifies database programming.Learn hands-on with practical examples, making your journey fun and effective. Learn PL/SQL's
8 min read
PL/SQL Fundamentals
PL/SQL Control & Loops
Decision Making in PL/SQLPL/SQL (Procedural Language/Structured Query Language) is Oracle's extension to SQL that allows for procedural programming within databases. It features various conditional statements to control the flow of execution based on specific conditions.In this article, We will learn about the various PL/SQ
5 min read
PL/SQL LoopsPL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. It is a block-structured language that
5 min read
PL/SQL For LoopPL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. With PL/SQL, you can fetch data from the table, add data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries. To fetch records, process dat
4 min read
PL/SQL While LoopOracle PL/SQL provides various loop structures that help developers execute a block of code multiple times based on certain conditions. The main loop structures include LOOP ... END LOOP, WHILE ... END LOOP, and FOR ... END LOOP. In this article, we will explore the WHILE loop in detail, including i
5 min read
PL/SQL Queries & Clauses
PL/SQL SELECT INTO Existing TablePL/SQL is a programming language that is used alongside SQL for writing procedural code such as stored procedures, functions, triggers, and packages within the Oracle Database. It was developed by Oracle Corporation and is widely used in database programming.PL/SQL is a programming language that has
5 min read
PL/SQL INSERT StatementThe PL/SQL INSERT statement is vital for adding new records to a database table. By specifying the table's name and providing values for its columns, users can populate their database with essential information. This functionality enables efficient data entry and ensures the completeness of datasets
3 min read
PL/SQL UPDATE StatementThe UPDATE statement in the PL/SQL(Procedural Language/ Structural Query Language) is the powerful SQL (Structured Query Language) command used to modify the existing data in the database table. In this article, we will explain the PL/SQL UPDATE Statement, its syntax, and examples in detail.PL/SQL U
6 min read
PL/SQL DELETE StatementIn PL/SQL(Procedural Language/Structured Query Language), the DELETE statement is the powerful command used to remove one or more records from the database table. It is an essential part of database management and enables the users to efficiently manage and maintain the data integrity by selectively
6 min read
PL/SQL WHERE ClauseThe WHERE clause in PL/SQL is essential for filtering records based on specified conditions. It is used in SELECT, UPDATE, and DELETE statements to limit the rows affected or retrieved, allowing precise control over data manipulation and retrieval.In this article, We will learn about the WHERE Claus
3 min read
PL/SQL ORDER BY ClauseIn PL/SQL, the ORDER BY clause is a vital tool that allows for the sorting of query results by one or more columns, either in ascending or descending order. In this article, We will learn about ORDER BY clause in PL/SQL, its syntax, functionality, and practical usage through examples.Understanding O
7 min read
PL/SQL GROUP BY ClauseThe GROUP BY clause in PL/SQL is a powerful tool used to organize data into aggregated groups based on one or more columns. It is essential for performing summary operations on large datasets, enabling efficient data analysis by grouping rows that share common values.In this article, We will learn a
7 min read
PL/SQL Operators
PLSQL : || OperatorThe string in PL/SQL is actually a sequence of characters with an optional size specification. The characters could be numeric, letters, blank, special characters or a combination of all. The || Operator in PLSQL is used to concatenate 2 or more strings together. The result of concatenating two char
2 min read
PL/SQL AND OperatorThe PL/SQL AND operator is used to combine multiple conditions in a WHERE clause of an SQL query. It allows you to refine your query by ensuring that all specified conditions are met. AND queries which help in filtering data more precisely and can be crucial for retrieving accurate results from a da
7 min read
PL/SQL LIKE OperatorThe PL/SQL LIKE operator is a powerful tool used in SQL queries to search for patterns in character data. It allows you to match strings based on specific patterns defined by wildcards. This operator is commonly used in SELECT, UPDATE, and DELETE statements to filter records based on partial or comp
6 min read
PL/SQL NOT OperatorPL/SQL, an extension of SQL in Oracle, offers various operators that allow us to perform logical operations on data. One such operator is the NOT operator, which is used to negate a condition, meaning it will return true if the condition is false and vice versa.The NOT operator is commonly used in c
6 min read
PL/SQL IS NULL OperatorThe IS NULL operator is a fundamental tool in PL/SQL used to determine the presence of NULL values in database columns. Understanding how to effectively use the IS NULL operator is crucial for database management, as it allows developers and analysts to identify and handle records with missing or un
4 min read
PL/SQL CASE StatementPL/SQL stands for Procedural Language Extension to the Structured Query Language and it is designed specifically for Oracle databases it extends Structured Query Language (SQL) capabilities by allowing the creation of stored procedures, functions, and triggers. The PL/SQL CASE statement is a powerfu
4 min read
PL/SQL Program Units
PL/SQL Data Structures & Error Handling
Index in PL/SQLPL/SQL, Oracle's extension to SQL, combines SQL with procedural programming features like loops, conditionals, and exception handling. It enables developers to create stored procedures, functions, triggers, and other database applications. As a block-structured language, PL/SQL allows seamless integ
5 min read
Exception Handling in PL/SQLAn exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the exception block which raises the exception thus helping the programmer to find out the fault and resolve it. There are two types of exceptions defined in PL/SQL User defined exception. System defi
7 min read
PL/SQL RecordsPL/SQL stands for Procedural Language/Structured Query Language. It is an extension of the Structured Query Language (SQL). A core feature of PL/SQL is its ability to work with complex data types, including PL/SQL records. PL/SQL records enable developers to group related data elements, creating a s
10 min read
Cursors in PL/SQLA Cursor in PL/SQL is a pointer to a context area that stores the result set of a query. PL/SQL CursorsThe cursor is used to retrieve data one row at a time from the results set, unlike other SQL commands that operate on all rows at once. Cursors update table records in a singleton or row-by-row man
3 min read