| Lesson 4 | Working with SQL developers |
| Objective | List techniques for working with SQL developers using Oracle AI Database 26ai. |
Effective SQL tuning is a shared engineering activity. Developers understand the application requirement, user interactions, and transaction boundaries. Database administrators contribute knowledge of database resources, execution plans, privileges, and operational constraints. Both groups need an application that returns correct results, responds predictably, and remains maintainable as its workload grows.
The useful question is not whether a developer or DBA wrote the statement. It is whether the team can explain what the statement must do, reproduce its behavior, and demonstrate that a proposed improvement preserves the result. Oracle AI Database 26ai provides diagnostic tools, but those tools cannot decide which business requirement is correct. That decision must precede performance testing.
Turn a vague request such as “make the search faster” into a testable agreement. Identify the transaction, expected number of rows, relevant data distribution, and acceptable response time. Decide whether the application needs the first screen of results quickly or must consume an entire report. These are different workloads, even when they start with similar SQL.
For example, an interactive lookup may need a small ordered result, whereas an overnight export must process every qualifying row. A plan that suits one requirement may be unsuitable for the other. Record which behavior the application actually uses rather than comparing a partly fetched query with a fully fetched query and calling the difference an improvement.
Agree on who supplies the test data, who reviews execution evidence, and who accepts the result. Include operational requirements such as concurrency, transaction duration, access controls, and the effect of new indexes on writes. Performance becomes part of the definition of done instead of an argument after deployment.
A useful tuning request contains enough information for another engineer to repeat the investigation. Send the exact SQL and relevant bind values with their data types, not a screenshot of a slow application. Identify the schema, PDB, database version, and the application operation that issued the statement. Keep sensitive data out of shared examples by using an approved representative dataset.
Separate database execution time from the rest of the request. Network transfers, repeated application calls, and rendering thousands of rows can dominate what a user experiences. A faster database statement does not necessarily fix a slow page if the application still makes hundreds of avoidable round trips.
Consider an administrative report listing users with no matching role grant in the current container. The following read-only example uses DBA_USERS and DBA_ROLE_PRIVS. It requires authorized access to those dictionary views and a connection to the intended PDB or container. Do not grant an application broad DBA privileges merely to run a tutorial query.
SELECT u.username
FROM dba_users u
WHERE NOT EXISTS (
SELECT 1
FROM dba_role_privs r
WHERE r.grantee = u.username
)
ORDER BY u.username;
The description matters. This query does not prove that a user has no effective privileges. A user may have direct privileges or access through PUBLIC. It is not a recursive analysis of role hierarchies or a test of roles enabled in a particular session. Oracle documents grants to both users and roles in DBA_ROLE_PRIVS.
NOT EXISTS expresses the absence requirement directly, but it is not a promise of better performance than NOT IN. With nullable data, those formulations can differ: a null returned by a NOT IN subquery can prevent expected rows from being returned. Check the actual constraints and intended treatment of nulls before declaring two statements equivalent. This general warning does not assert that the dictionary query contains null grantees. See Oracle's IN condition documentation.
Apply the same discipline to other rewrites. Adding DISTINCT may hide duplicates caused by an incorrect join. Removing an order clause changes a requirement if the application relies on ordered results. Changing a comparison can introduce an implicit conversion. Review the expected answer first, then decide which alternatives are legitimate performance candidates.
Copying source data into tables named temp1 and temp2 does not make those tables temporary. An ordinary CREATE TABLE ... AS SELECT creates a permanent table. Explicit temporary-table syntax has different lifecycle rules. Oracle's CREATE TABLE reference distinguishes these table types and their prerequisites.
Materializing intermediate results can be appropriate for a designed workload, but it adds responsibilities: storage, privileges, refresh behavior, concurrency, and cleanup. Separate statements may observe different committed states, and copied data can become stale. Ordinary permanent-table DDL also has transaction implications. Do not introduce it casually into an application transaction to imitate an old tuning example.
Measure the whole proposed operation. Timing only the final select after data has already been copied excludes the cost that made the result available. For this dictionary report, start with the direct query and inspect its execution evidence. There is no demonstrated reason to build extra tables simply because a historical example reported a shorter elapsed time.
Oracle 26ai tuning should not be framed as a contest between rule-based and cost-based optimization. Do not restore a RULE hint as a modern tuning strategy. Begin with correct SQL, relevant metadata and statistics, and evidence from the workload that needs improvement.
When a plan appears unsuitable, investigate why. A predicate may select many more rows than expected, a bind value may represent an unusual part of the data, or a join condition may be missing. Discuss statistics changes with the DBA through established DBMS_STATS procedures. Blindly adding a hint can hide the symptom without addressing the cause.
Optimizer goals also need context. ALL_ROWS addresses overall resource use, whereas FIRST_ROWS(n) targets an initial number of rows. Neither replaces a clear application requirement or guarantees a particular latency. Avoid copying the legacy bare FIRST_ROWS hint into new examples without a reason. Oracle explains these choices in Influencing the Optimizer.
EXPLAIN PLAN is useful for examining a proposed execution plan, but it does not execute the target statement. Its plan can differ from the one used by an actual cursor. For a tuning investigation, connect the observed execution to its SQL ID and child cursor rather than treating a predicted plan as runtime evidence. See Explaining and Displaying Execution Plans.
In a controlled test session, collect row-source statistics for the example and fetch all rows when measuring complete execution:
SELECT /*+ gather_plan_statistics */ /* lesson4_role_check */ u.username
FROM dba_users u
WHERE NOT EXISTS (
SELECT 1
FROM dba_role_privs r
WHERE r.grantee = u.username
)
ORDER BY u.username;
Then display the cursor in the same session:
SELECT *
FROM TABLE(
DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST')
);
The null SQL ID selects the last statement executed by the session. Client housekeeping or another statement can change that selection; use the verified SQL ID and child cursor number explicitly when necessary. The target execution must have collected statistics. A partial fetch does not describe the work of consuming the entire result.
DISPLAY_CURSOR requires appropriate access to V$SQL, V$SQL_PLAN, V$SESSION, and V$SQL_PLAN_STATISTICS_ALL. Arrange approved diagnostic access with the DBA. Scope instrumentation to the investigation because it adds overhead. These examples are illustrative, not measured results. Oracle documents the interface and permissions in DBMS_XPLAN.
Review estimated rows, actual rows, starts, buffer work, and available I/O statistics together. A large estimate error can help locate an investigation, but interpret repeated operations carefully: accumulated rows across many starts are not directly comparable to a per-start estimate. Do not sum every displayed elapsed time as though all operations represented independent work.
A full table scan is not automatically a defect. Reading a substantial part of a table can favor a scan, while an index may help a selective lookup. Index access may still require many table-block visits. Evaluate the work performed for this request rather than counting how many times the word “INDEX” appears. Oracle describes these tradeoffs in Optimizer Access Paths.
During a joint review, ask a specific question at each suspicious point: Why did this operation produce so many rows? Is the filter applied where expected? Are repeated calls necessary? Does the requested output justify the volume transferred? These questions produce testable hypotheses. “The plan looks complicated” does not.
Keep the baseline and candidate SQL under version control or in the review record. Test one justified change at a time, such as correcting a predicate, avoiding redundant work, or adding an appropriate index. Record the reason for the change before running it so the result can be compared with the hypothesis.
Use representative inputs, including common values, skewed values, missing values, and empty results. A query tuned for one convenient parameter can regress badly for another. Check result values and duplicate counts. A set comparison alone may miss a change in multiplicity, and comparing only row counts can miss entirely different rows.
Repeat measurements and document conditions. Cache state, concurrent work, and client fetch behavior affect observations. Do not flush shared caches on a production system merely to produce a neat test. Compare like with like: the same required output, similar workload conditions, and the same scope of measured work. Report variability instead of selecting only the best run.
Review tradeoffs beyond the isolated select. A new index consumes space and adds maintenance work to data changes. A rewrite that reduces one request's latency may hold resources longer under concurrency. Acceptance should cover the application operation and its important neighboring workloads, not simply a lower number in a single SQL worksheet.
Document what changed, why it was expected to help, which tests were performed, and what remains uncertain. Keep a compact comparison that another developer or DBA can understand without reconstructing the entire conversation. Use measured values from your environment, not illustrative numbers copied from a lesson.
| Record | Purpose |
|---|---|
| Baseline and candidate SQL | Identify the exact change and preserve a rollback reference. |
| Inputs and expected results | Show that correctness was checked for relevant cases. |
| Execution identity and plan evidence | Associate observations with the intended cursor and environment. |
| Repeated latency and resource observations | Separate a repeatable improvement from an isolated result. |
| Tradeoffs and acceptance decision | Explain operational consequences and who reviewed them. |
After deployment, compare the important application indicators with the baseline and use agreed rollback criteria if the change regresses. A successful test is evidence for a decision, not a guarantee that every future data distribution will behave identically. Retain enough context to investigate later changes in workload or execution plans.
Suppose a customer search has become slower as the application grows. Before proposing an index, the developer explains which filters users actually combine and whether they need a total count or only the next page. The DBA checks the relevant plan evidence and data distribution. Together they choose one representative request and agree on how its complete response will be measured.
The first experiment might remove an unnecessary second query rather than change the plan of the first. Another might correct a data-type mismatch between an application parameter and the database column. Neither proposal is accepted simply because it sounds plausible. The team checks the result, observes the work, and records whether the evidence supports the change.
Now repeat the accepted candidate with a common filter value and a much less selective value. If the latter returns substantially more data, decide whether the application requirement itself needs refinement. Silently truncating results would change correctness; deliberately designing pagination with a stable ordering is a product and database decision. State that decision in the review so a later maintainer does not mistake it for an accidental restriction.
Keep correctness tests deterministic: expected values, duplicate handling, and required ordering should not vary with machine load. Performance checks need a controlled environment and tolerances suitable for that environment. Avoid failing every build because one elapsed-time sample was slightly slower, but investigate sustained changes in latency or resource work.
Assign an owner to the accepted change and retain the baseline evidence. If production behavior differs, compare workload and configuration before making another adjustment. This makes tuning a sequence of explainable decisions instead of an accumulation of hints, indexes, and exceptions whose purpose nobody remembers.
The most effective DBA assistance is repeatable. Offer short pair-review sessions, maintain a small set of examples, and explain the reason behind each standard. A useful tip sheet might cover typed binds, explicit join conditions, appropriate result limits, and the evidence needed for a tuning request. Keep it aligned with the team's actual application rather than collecting universal-sounding rules.
Use SQL Trace and TKPROF when a targeted investigation needs statement-level execution information beyond an initial plan review. Control trace scope and duration, and handle trace contents according to the organization's data rules. SQL*Plus, SQLcl, or an appropriate development interface can run the examples. The workflow matters more than the editor. See Oracle's application tracing guidance.
Keep optional management features distinct from the basic cursor example. AWR/ASH, SQL Tuning Advisor, and Real-Time SQL Monitoring have licensing or service-entitlement requirements. Confirm the applicable edition, service, and contract before using them. Access to a menu or API does not establish entitlement, and DISPLAY_CURSOR should not be confused with DISPLAY_AWR. Consult the Oracle 26ai licensing documentation.
Finally, make performance discussions safe and concrete. Ask for a reproducible case, explain the evidence, and agree on the next experiment. Developers and DBAs learn more from a measured correction than from criticism of who wrote the SQL. The next lesson examines SQL inside stored procedures, where the same requirements for correct results, deliberate privileges, and measured performance still apply.