Dung (Donny) Nguyen

Senior Software Engineer

SQL Execution Plan

An SQL Execution Plan is a step-by-step roadmap generated by a database management system, such as Oracle Database, that details how a SQL statement will be executed. The execution plan describes the path taken to retrieve the data, including:

  1. Access Methods: How the database retrieves data from tables (e.g., full table scans, index scans).
  2. Join Methods: How tables are joined (e.g., nested loops, hash joins).
  3. Sorting Operations: How data is sorted and filtered.
  4. Cost Metrics: Estimated resource costs (CPU, memory, I/O) for each operation.

Execution plans are crucial for understanding and optimizing SQL performance, as they highlight inefficiencies such as unnecessary full table scans or incorrect index usage.


How to Work with SQL Execution Plans in Oracle Database

1. Generate Execution Plans

There are several methods to generate and view execution plans in Oracle:

a. EXPLAIN PLAN Statement

EXPLAIN PLAN FOR
SELECT * FROM employees WHERE department_id = 10;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY());

The DBMS_XPLAN.DISPLAY function formats and displays the execution plan from the PLAN_TABLE.

b. Using SQL Developer

c. Using AUTOTRACE

SET AUTOTRACE ON
SELECT * FROM employees WHERE department_id = 10;

d. V$SQL_PLAN View

SELECT * FROM V$SQL_PLAN WHERE SQL_ID = '<sql_id>';

2. Interpret Execution Plans

Key columns in the plan output:


3. Optimize SQL Using Execution Plans

a. Analyze Inefficiencies

b. Add or Modify Indexes

c. Rewrite SQL Statements

d. Gather Statistics

EXEC DBMS_STATS.GATHER_TABLE_STATS('SCHEMA_NAME', 'TABLE_NAME');

e. Use SQL Hints

SELECT /*+ INDEX(employees emp_index) */ * FROM employees WHERE department_id = 10;

4. Monitor Actual Execution with Real-Time Statistics

For real execution plans (not hypothetical):

SELECT * FROM V$SQL_MONITOR WHERE SQL_ID = '<sql_id>';

By understanding and working with SQL execution plans, you can diagnose and resolve performance issues in Oracle Database, ensuring optimal query execution.