| Lesson 2 | SQL as a declarative language |
| Objective | Explain how Oracle 26ai chooses SQL access paths and why query rewrites must preserve the required results. |
SQL describes the result you want without requiring you to prescribe every operation that retrieves it. In Oracle AI Database 26ai, the optimizer chooses physical access paths and combines them into an execution plan. The term hidden access paths refers to this abstraction: implementation details are absent from ordinary SQL text, but you can inspect them through plan tools.
Consider a school application that needs the names of students on the honor roll. The query must identify the relevant tables, matching conditions, and output columns. It does not ordinarily need to specify which index to open, which table blocks to visit, or which join algorithm to use. Those are separate decisions about how to obtain the requested rows.
Lesson 1 introduced EXPLAIN PLAN and the distinction between estimates and execution evidence. This lesson explains why that distinction matters when you read SQL or consider rewriting it. Two statements that look different may lead to similar processing, while two statements that look interchangeable may return different numbers of rows.
The logical requirements define correctness. SELECT identifies the output expressions, FROM names data sources, and WHERE and ON describe conditions and relationships. GROUP BY and aggregate expressions define grouping when needed. ORDER BY specifies result ordering when the application requires it.
Naming tables and join conditions does not make SQL less declarative. These clauses tell Oracle what the result means. They do not instruct Oracle to follow a particular sequence of pointer traversals or table reads. A written join order is not necessarily the physical join order, and the position of a predicate in the text is not a reliable indication of when it is evaluated.
| Logical requirement | Possible implementation decision |
|---|---|
| Return students who have an honor-roll entry. | Choose an appropriate membership or join strategy. |
| Match rows by student number. | Use a suitable index or scan the relevant data. |
| Return a student's name. | Obtain the required columns through the available access paths. |
| Order the results when requested. | Use an operation that satisfies the required ordering. |
This separation gives the database room to adapt as data volumes, indexes, and statistics change. It also places responsibility on the developer to express the result precisely. An optimizer cannot repair an incorrect business rule simply by selecting a different access path.
During parsing, Oracle checks the statement and determines whether compatible executable code can be reused. A soft parse can reuse a suitable cached cursor. When a hard parse is needed, Oracle performs optimization and row-source generation before executing the statement. Reusing an already prepared cursor can avoid additional parse calls altogether.
Cost-based optimization uses information such as object and index metadata, available optimizer statistics, and optimizer settings. Oracle considers transformations and alternative plans, estimates their costs, and chooses among the alternatives it considers. This is an estimation process, not a guarantee of the fastest possible execution under all circumstances.
The row-source generator produces executable operations from the selected plan. Reusable cursor structures are held in the library cache within the shared pool. The SQL engine executes the row sources and the client fetches query results. The library cache is a reuse mechanism; it is not the component that executes the query.
This diagram simplifies SELECT processing. It does not show every error path, cursor-management operation, or execution-time adaptation. It also does not mean that Oracle gathers new table statistics for every query. Available statistics inform optimization; statistics collection is a separate activity.
Consistent SQL and correctly typed bind variables can support reuse, but identical statement text alone does not guarantee that an existing child cursor is compatible. Object resolution, privileges, and relevant execution settings also matter. For performance work, record the actual application context rather than assuming that a query submitted from a separate tool behaves identically.
PL/SQL is Oracle's procedural extension to SQL. It provides variables, conditional statements, loops, subprograms, and exception handling. These features let a program coordinate database operations and implement surrounding business logic. They do not turn the SQL statements themselves into instructions for a specific physical access path.
A stored procedure can decide when to execute a query, what values to supply, and what to do with its result. The SQL engine still processes the SQL, and the optimizer still determines its execution strategy. Moving a query into a procedure does not automatically make its table access faster.
Use set-based SQL when it expresses the required operation clearly. Use procedural control when the application needs it. A loop that issues a query for every student introduces a different workload from a single membership query, so it should not be added merely to make the processing look explicit.
Stored program units can provide useful interfaces, centralize logic, and reduce application round trips in suitable designs. Those benefits must be distinguished from the cost of an individual SQL statement. This lesson therefore focuses on SQL semantics and access paths rather than introducing unrelated procedures, triggers, or exception-handling examples.
Assume two illustrative teaching tables: STUDENT contains student_number and student_name, and HONOR_ROLL contains student_number. These are example application tables, not objects installed automatically with Oracle. To execute the examples, use a learning database with equivalent tables, compatible column types, and appropriate permissions.
The business request is to return each qualifying student row when that student's number appears on the honor roll. Start by deciding whether multiple honor-roll entries should multiply the result. A real honor-roll table might contain entries for different terms, which would require a term condition if the request concerns only one term.
SELECT s.student_name
FROM student s
WHERE s.student_number IN (
SELECT h.student_number
FROM honor_roll h
);
This query keeps a STUDENT row when its number matches a value returned by the subquery. Repeating the same matching number in HONOR_ROLL does not multiply that outer row. This is membership testing, rather than a request to return every matching pair.
The subquery is noncorrelated: it does not reference the outer alias s. That syntactic observation does not establish how many scans Oracle performs. Do not infer that it must scan HONOR_ROLL separately for every student. The optimizer can transform eligible statements before choosing physical operations.
SELECT s.student_name
FROM student s
JOIN honor_roll h
ON h.student_number = s.student_number;
The equality condition relates a student row to matching honor-roll rows. If two honor-roll entries match one student, the join returns two result rows for that student. Selecting only the name does not remove this multiplicity.
The two queries produce the same result multiplicities when each student number has at most one matching honor-roll row. A suitable declared unique or primary-key constraint can enforce that condition. Do not assume such a constraint exists simply because the column name sounds like an identifier.
The diagram's instruction to validate runtime statistics is advice for the person investigating the query. It does not mean Oracle automatically verifies that a rewrite satisfies the application's performance goals.
Imagine that student 101 is named Alex and has two matching HONOR_ROLL rows. Query A returns Alex once for that STUDENT row. Query B returns Alex twice. These are different results even if one query completes sooner. This is a logical example, not a reported database execution.
Now imagine a different student, number 202, also named Alex. Both students can legitimately appear in the output. Adding DISTINCT to student_name would merge equal names and could conceal a valid student. It is not a general repair for a join that changed the required multiplicity. Use student identifiers when validating who is represented, even when the final display requests names only.
Neither query guarantees row order without ORDER BY. A NULL student number does not establish an equality match in these positive predicates. A NULL among honor-roll values does not itself qualify an unmatched student. Keep this explanation scoped to these queries: negated predicates such as NOT IN and NOT EXISTS require separate attention to NULL semantics.
SELECT s.student_name
FROM student s
WHERE EXISTS (
SELECT 1
FROM honor_roll h
WHERE h.student_number = s.student_number
);
This version asks whether a matching honor-roll row exists. The subquery references s, so it is correlated. It still does not require Oracle to implement a literal row-by-row application loop. The optimizer may transform it into an equivalent strategy.
For the positive equality test shown here, EXISTS expresses the same membership requirement as Query A, including avoiding multiplication from repeated inner matches. It is not universally faster than IN. Choose a formulation that expresses the requirement clearly, then inspect and measure the relevant execution.
Subquery unnesting lets Oracle incorporate an eligible subquery into a broader optimization problem. This can make additional access paths, join orders, and join methods available. Consequently, a subquery in the SQL text need not remain a separate-looking operation in the displayed plan.
A semijoin returns a qualifying row from one input when a match exists in the other, without multiplying that row for additional matches. Oracle can use semijoin strategies for eligible membership and existence queries. The physical implementation can involve nested loops, a hash join, or a sort merge join, depending on the situation.
A semijoin and an ordinary inner join do not have identical duplicate-handling requirements. The optimizer must preserve the meaning of the original statement, taking relevant constraints into account. Do not expect every IN expression to be unnested or every formulation to produce the same plan.
This explains why syntax-based performance rules are unreliable. A query written with IN may already receive an efficient join-like implementation. Replacing it with JOIN might change nothing useful, or it might change the result. The legacy assertion that the join is ten times faster has no supporting measurements for this Oracle 26ai example.
Use EXPLAIN PLAN and DBMS_XPLAN.DISPLAY to inspect an estimated plan in the explaining environment. Use DBMS_XPLAN.DISPLAY_CURSOR to inspect the relevant cached cursor when investigating executed SQL. Identify the appropriate SQL_ID and child cursor, and obtain the required access through the DBA.
Actual row-source statistics must have been collected for the execution being studied. Requesting ALLSTATS LAST only displays available statistics; it does not retroactively instrument an earlier execution. Check whether the client fetched all rows or stopped after a preview, because the work observed may differ substantially.
Read the predicates, row estimates, and notes alongside the operation names. A full-table scan may be suitable for a small table or a query that needs much of its data. An index is not an automatic improvement when many scattered table rows must be visited. Estimated cost is not elapsed seconds, and a lower estimate does not prove a faster application.
A change that improves one tiny sample may not help a larger workload or a different input distribution. Conversely, unchanged SQL may receive a different plan after statistics or schema changes. Keep the query's logical contract stable while investigating those physical decisions.
The next lesson examines Oracle's PLAN_TABLE, where EXPLAIN PLAN records estimated operations. Oracle supplies default plan-table infrastructure, so understanding its role comes before deciding whether a separate table is needed.