KB · Oracle Database · Script

Get the SQL text and execution plan for a SQL_ID (dbms_xplan.display_cursor)

Oracle Database · Script · Verified on Oracle 11.2 and 23ai · Updated 2026-12-03

Three small scripts for the step after you've found a SQL_ID:

ScriptAnswers
getsql.sqlThe plan the database is actually using for this cursor, from the shared pool
gsql.sqlThe SQL text for a SQL_ID on a given instance
plan.sqlWhat plan would the optimizer choose for a statement I paste in?

Usage

SQL> @getsql.sql 0ycvb78r4383w 0
SQL> @gsql.sql 0ycvb78r4383w 1

getsql.sql takes the SQL_ID and the child number (0 for the first child; v$sql lists them all). For plan.sql, edit the statement inside it, then run @plan.sql.

getsql.sqlMIT · Download ·
-- getsql.sql: execution plan of a cursor in the shared pool (dbms_xplan.display_cursor)
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/
--
-- Usage: @getsql.sql <sql_id> <child_number>
--        @getsql.sql 0ycvb78r4383w 0

set echo off
set lines 400
set trims on
col PLAN_TABLE_OUTPUT format a200
set pages 0

select * from table(dbms_xplan.display_cursor('&1',&2));

curl -O https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/getsql.sql

gsql.sqlMIT · Download ·
-- gsql.sql: full SQL text for a SQL_ID on one instance
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/
--
-- Usage: @gsql.sql <sql_id> <inst_id>

select sql_text from gv$sql where sql_id = '&&1' and inst_id = '&&2'
/

curl -O https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/gsql.sql

plan.sqlMIT · Download ·
-- plan.sql: explain plan template: paste a statement, see its plan
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/
--
-- Usage: edit the statement, then @plan.sql

set lines 165
set trims on
col PLAN_TABLE_OUTPUT format a165
set pages 500
set long 100000000

-- Replace the statement below with the one you want to explain.
explain plan for
select * from mytable where x = :1;

select * from table(dbms_xplan.display());

curl -O https://hashjoin.com/kb/oracle/sql-text-and-plan-for-a-sql-id/plan.sql

Gotchas

What it reads

gv$sql v$sql_plan

Tired of fixing the same thing twice?

HASHJOIN turns the checks and fixes your on-call runs by hand into tooling that gives the same answer every time. Fixed scope, and you own all of the code.