SQL Tuning Tools   «Prev  Next»

Lesson 1

SQL Tuning Tools and Development Practices in Oracle 26ai

A SQL statement can return the correct answer and still make an application difficult to use. A search may take too long, a report may consume resources needed by other sessions, or thousands of small requests may repeatedly perform the same avoidable work. SQL tuning starts by identifying which of these problems matters to the application.

This module explains how developers and database administrators work together to develop and improve SQL in Oracle AI Database 26ai. Its objective is to connect measurable performance requirements with practical investigation tools, coding standards, and a repeatable review process. The tools provide evidence; the team must interpret that evidence in the context of the business operation.

The following lessons cover four connected responsibilities:

  1. Identifying DBA roles in SQL tuning.
  2. Creating and enforcing SQL standards.
  3. Working with SQL developers.
  4. Using SQL inside stored procedures.

These responsibilities apply during design and testing as well as when investigating production problems. An introductory tuning workflow should help a team ask better questions before it changes an index, adds a hint, or adjusts a database setting.

Define the performance requirement first

Suppose a customer lookup must return its first screen within two seconds for at least 95 percent of requests under an agreed concurrent load. That is a hypothetical requirement, not a benchmark result. It identifies an operation, a latency target, and a test condition. The team must also define the data volume, search patterns, and amount of information displayed.

Response time describes how long a request takes from the user's perspective. Throughput describes the amount of work completed in a period. A change that speeds up one isolated query by consuming much more CPU may reduce the throughput of the entire application. Conversely, a batch report can meet its completion deadline without returning its first row immediately.

Measure the part of the operation that the requirement concerns. Database execution time is only one component of an application response. Waiting for an available pooled connection, making network round trips, fetching rows, converting results, and rendering a page can also matter. A database plan alone cannot show all of these costs.

Correctness remains an acceptance criterion. A rewrite that omits customers with no orders, changes duplicate handling, or treats an unknown price as zero may run faster while answering a different question. Preserve result meaning, access controls, and transaction behavior when comparing alternatives.

Make performance a shared responsibility

The developer understands what the application needs to do and how it supplies values to SQL. The DBA understands the database's shared workload, operational constraints, and available diagnostic facilities. Neither perspective is sufficient by itself. A slow statement might reflect an inefficient join, an unexpected parameter distribution, excessive client calls, or contention elsewhere in the system.

A useful investigation begins with a reproducible description rather than a request to “tune this query.” Include the SQL text, relevant parameter values and data types, the expected result, and the circumstances under which it becomes slow. Sensitive values should be protected or replaced with representative test data that preserves the performance characteristics being investigated.

The DBA can then help check the execution context, available indexes, optimizer statistics, and competing resource demands. The developer can verify application timing and investigate whether the same work is being requested repeatedly. Approval responsibilities vary by organization; the important requirement is a clear owner for testing and release, not a universal rule that a DBA must approve every statement.

Follow a repeatable tuning workflow

  1. Describe the operation. Identify the business request, required output, response-time or throughput target, and relevant workload conditions.
  2. Establish a baseline. Record elapsed time, execution frequency, representative inputs, and the environment. Distinguish a single slow execution from a frequently executed statement with a large aggregate cost.
  3. Collect evidence. Find the relevant execution plan and, where available, runtime statistics. Compare application observations with database evidence rather than assuming both measure the same interval.
  4. Form a specific hypothesis. For example, determine whether an incorrect cardinality estimate contributes to an unsuitable join strategy, or whether repeated round trips dominate the request.
  5. Change one relevant factor. A targeted SQL rewrite, index change, statistics correction, or application adjustment is easier to assess than several unrelated changes made together.
  6. Repeat and compare. Test the same operation and parameter cases, verify results, and check effects on concurrent work. Record both improvements and regressions.

Document cache conditions and fetch behavior when comparing measurements. Timing a query that retrieves ten displayed rows is not equivalent to timing one that fetches the entire result set. Repeated tests help reveal variability, but flushing production caches to create an artificial starting point disrupts other work and is not an appropriate introductory experiment.

The handoff between developer and DBA should include the SQL_ID and child cursor when available, the tested schema, relevant indexes, parameter types, observed timings, plan evidence, and the proposed change. Keep a rollback approach with the change record. This makes the investigation reproducible and allows another person to distinguish a measured improvement from an attractive-looking plan.

Choose tools that answer the current question

Oracle 26ai supports several ways to inspect SQL behavior. Start with the smallest investigation that can answer your question. A command-line client, a plan display, and a trace report serve different purposes; none should be treated as a replacement for knowing what the application is trying to accomplish.

Tool or facilityUseful questionImportant limit
SQL*Plus or SQLclCan I reproduce the SQL and inspect its results in a controlled session?The client's environment and fetch behavior may differ from the application.
EXPLAIN PLAN and DBMS_XPLAN.DISPLAYWhat plan does the optimizer propose in this environment?The target statement is not executed; its runtime plan can differ.
DBMS_XPLAN.DISPLAY_CURSORWhat plan belongs to a loaded cursor, and what execution statistics were collected?Select the intended cursor. Runtime statistics require collection and appropriate privileges.
SQL trace and TKPROFHow is time and work distributed across parse, execute, and fetch activity?Scope collection carefully and account for overhead and access requirements.
AWR, ASH, SQL Tuning Advisor, and Real-Time SQL MonitoringDo historical, sampled, advisory, or monitored execution details help explain the problem?Check the particular facility's availability and licensing before use.

Separate an explained plan from execution evidence

EXPLAIN PLAN is useful for examining a proposed access path, but it does not establish how long the target query took. Differences in bind values, session settings, or other execution conditions can make the actual plan different. When diagnosing an observed execution, identify its cursor and inspect that evidence rather than assuming a newly explained plan reproduces it.

DBMS_XPLAN.DISPLAY_CURSOR can display the plan of a cursor still available in the cache. With suitable statistics collected during execution, formats such as ALLSTATS LAST help examine the last execution's row-source activity. The display format does not retroactively collect missing measurements. A controlled diagnostic execution can use gather_plan_statistics; enabling detailed collection across an instance is not necessary for this introductory lesson.

Request the required diagnostic-view access through the DBA instead of routinely connecting as an administrator. Also confirm that the SQL_ID and child number belong to the query under investigation. A client may execute helper statements between your query and a “last statement” display. A missing cursor or missing runtime data is an evidence limitation, not proof that the query did no work.

Check feature entitlement before advanced diagnostics

Oracle Diagnostics Pack covers AWR and ASH functionality. Oracle Tuning Pack includes SQL Tuning Advisor and Real-Time SQL Monitoring and requires Diagnostics Pack where the packs are separately licensed. Edition restrictions and cloud-service inclusions vary. Check the applicable offering and agreement before using these facilities; an enabled parameter, accessible view, or visible menu is not itself evidence of entitlement.

Data sources also matter when evaluating a package such as DBMS_XPLAN. Displaying a loaded cursor and retrieving information from AWR are not interchangeable licensing situations. The Oracle 26ai Licensing Information is the reference for these distinctions. The small bind-variable example below does not require an AWR report or SQL Tuning Advisor run.

Design applications to avoid unnecessary work

Tuning tools cannot compensate for every application-design problem. Repeatedly requesting data that has already been retrieved, transferring unused columns, or issuing one query per row can create avoidable work before an optimizer decision becomes the main issue. Examine the request pattern as well as the SQL statement.

Model data around real transactions

Start with entities, relationships, constraints, and data types that represent the business accurately. Then examine the operations that read or change those entities most often. A customer lookup, an order-entry transaction, and a month-end aggregate may need different access paths even when they use related tables.

Index design is a workload decision. An index may reduce the work needed to locate selected rows, but it also occupies storage and must be maintained as data changes. A full scan can be appropriate for a query reading a large proportion of a table. Neither the presence of an index nor the absence of a full scan proves that a query is efficient.

Optimizer statistics describe data characteristics used in estimating plans. Investigate whether those statistics represent the workload's data before prescribing a change. Avoid collecting statistics or adding indexes simply because a report is slow; first establish how that action addresses the suspected cause and how its effects will be tested.

Reuse connections without exhausting the database

Opening a new physical database connection for every small request adds work that a connection pool can often avoid. A bounded pool lets the application borrow an available connection, perform its database work, and return it reliably. Returning a logical connection to a pool is different from repeatedly creating and destroying physical connections.

Pool sizing must reflect application concurrency and database capacity. Too few connections can make requests wait for the pool; too many can overload the database. One permanent connection for every web user is not a general design rule. Review transaction cleanup, session state, timeouts, and the actual driver's pooling behavior.

Connection pooling and statement caching solve different problems. Pooling reuses connections; statement caching can reuse prepared statements associated with those connections. Both require disciplined resource handling. Close or release application resources as the driver requires, and avoid keeping transactions open while waiting for a person or an unrelated external service.

Understand hard parsing, soft parsing, and statement reuse

Before Oracle can execute SQL, it needs a suitable executable representation. A hard parse includes optimization and generation of executable work when a reusable representation is unavailable. A soft parse reuses suitable shared SQL instead of repeating that work. Soft parsing still has overhead, so reducing unnecessary parse calls is useful as well as reducing hard parses.

The distinction is not simply “first execution” versus “second execution.” A statement submitted for the first time by one session may reuse SQL already available from another session. A previously executed statement may need new work if its cursor is no longer available or reusable. Matching SQL text alone does not guarantee that the required child cursor is compatible with the current execution environment.

Prepared statements, correctly typed binds, and appropriate statement caching help repeated operations reuse work. They do not promise that every input value will share one plan forever. Data distribution, cursor compatibility, and optimizer behavior still matter. Review the executed cursor instead of assuming that an adaptive feature automatically fixes an unsuitable plan during every execution.

Bind changing data values

The following illustrative script uses SQL*Plus or SQLcl and assumes the optional HR sample schema is installed and readable. If it is unavailable, use an authorized training table with equivalent columns. These examples were not executed as part of this lesson revision, and no row count or index choice is promised.

VARIABLE p_last_name VARCHAR2(25)
EXEC :p_last_name := 'King';

SELECT employee_id, first_name, last_name
FROM hr.employees
WHERE last_name = :p_last_name;

VARIABLE and EXEC are client commands. The SELECT is SQL, and its unquoted placeholder receives a value from the client. An application supplies that value using its database driver's parameter API rather than issuing these client commands.

To look up another exact surname, change the bound value while retaining the SELECT text. Equality is intentional here; LIKE would be appropriate for a search that actually needs pattern semantics. Bind variables represent data values, not table names, column names, or arbitrary SQL keywords.

Binding values avoids concatenating them into SQL syntax and supports reuse. It does not make all dynamically constructed SQL safe, eliminate every hard parse, or guarantee the best access path for every input. Test representative values, including common and rare matches, instead of judging a parameterized statement from one convenient example.

Turn an investigation into a maintainable change

SQL standards make successful practices repeatable. Useful standards cover parameter handling, data types, transaction boundaries, error handling, resource cleanup, and the evidence required for a performance-sensitive change. Consistent formatting helps review, but formatting alone does not establish correctness or efficiency.

Stored procedures can provide a stable interface and centralize database operations. They do not automatically improve an inefficient SQL statement merely by containing it. Review both the SQL and the way the application calls it. Later in this module, you will examine how procedures fit the development process rather than treating them as a universal tuning shortcut.

Before release, check the changed operation alongside related requests and document how to reverse the change if a regression appears. Keep before-and-after evidence tied to the tested environment. A successful development test supports a release decision, but it does not guarantee identical production timing under a different workload.

Continue with DBA roles in SQL tuning

The foundation is a shared process: define acceptable behavior, reproduce the operation, collect the right evidence, and validate a focused change. Tools become more useful when the developer and DBA agree on the question they are answering. The next lesson examines the DBA's responsibilities in SQL tuning and how those responsibilities support the development team.

Oracle 26ai references

SEMrush Software 1 SEMrush Banner 1