Explain Statement (explainStatement)
Syntax
%%{init: {
'theme': 'base',
'flowchart': { 'padding': '7', 'nodeSpacing': '20', 'rankSpacing': '20' },
'themeVariables': {
'fontSize': '11px',
'fontFamily': 'Arial'
}
}}%%
flowchart LR
explainStatement_start((START))
explainStatement_start --> explainStatement_0_0[EXPLAIN]:::quoted
explainStatement_0_0 --> explainStatement_0_1[ANALYZE]:::quoted
explainStatement_0_0 --> explainStatement_0_2[<a href="Invantive UniversalSQL/Grammar/Query Statement/Select Statement#selectStatement" class="internal-link">selectStatement</a>]
explainStatement_0_1 --> explainStatement_0_2
explainStatement_0_2 --> explainStatement_end((END))
Purpose
The explain statement shows how Invantive UniversalSQL executes a select statement. It returns one row per operation of the execution plan, such as the read of a table, a join, a filter or a sort.
With analyze, the select statement is executed to the end and its rows are discarded. The explain analyze statement then returns one row per step that was executed, with the number of rows, the duration and what the step counted. The last row has the kind Total and holds the totals of the statement.
Only a select statement can be explained, so explain analyze never changes data. The words explain and analyze remain available as names of columns, aliases and tables. Available from release 28.0 and the beta release 27.1 before it.
The columns of the result:
STEP_IDandPARENT_STEP_ID: the number of the operation and of the operation that consumes its rows. The first row is the explained statement itself, which has no parent. The row of the totals has no number.DEPTH: the depth below the explained statement.KIND: what the operation does, such asDataContainerRead,Join,SemiJoin,Filter,Sort,GroupBy,ToporProjection.OPERATION,ALIASandPARAMETERS: the operation in words, the alias of its result and what it works on, such as the condition of a join or the order of a sort.ALGORITHM: how a join matches its rows. The values areindex join on columns,index join on expressionsandnested loop, followed for a nested loop by the reason why no index could be used. When both tables of a join declare their number of rows, an index join on columns is followed by what the cost model decided on the key set:key set of at most ... keyswhen the distinct values of the left side may be handed to the right side as a filter, orleft input streamed, no key setwhen the right side is estimated far smaller. When the cost model joined the tables in another order than thefromclause, the operationColumns in the order of the from clauseshowsjoin order by estimate:followed by the aliases in the order chosen, and; rows put back in the order as writtenwhen the rows are sorted back into the order of thefromclause. For a long order only the first aliases are shown, followed by the number of tables;PARAMETERSof the same row holds the whole order. Forexplainthis is the plan. Forexplain analyzeit is the choice that was made on the actual rows.ESTIMATED_ROWS: for the read of a table, the number of rows of the table as the data container declares it, before any filter. For a join and a filter, the number of rows the cost model expects, worked out from the declared rows, the declared primary key and the conditions. It is empty when the data container declares nothing. Compare it withROWS_OUTof the same row.ROWS_IN,ROWS_OUT,DURATION_MSandHEAP_BYTES_ALLOCATED: the rows received and handed on, the duration in milliseconds and the bytes allocated, both including the steps below. On the row of the totals,ROWS_INholds the rows read from all tables andROWS_OUTthe rows returned by the statement.DURATION_EXCLUSIVE_MS,CPU_EXCLUSIVE_MSandHEAP_BYTES_EXCLUSIVE: the wall-clock time in milliseconds, the processor time in milliseconds and the bytes allocated by the step itself, without the steps below it. Rows are pulled through the plan from the top, so a table read lives from its first row to its last andDURATION_MSof that read also holds the time its consumers spent between two of its rows. The exclusive figures are measured instead on every request for a row: from the moment the consumer asks until the row is handed over, less the same figure of the steps below. They show where the time and the memory of a statement went. A step whose rows are not requested through the operators of the engine has empty exclusive figures, and its work is counted in the step above it. The processor time and the allocation are those of the thread which requested the rows; when a request of a step continues on another thread, as with a data container that waits for a platform, its processor time and allocation are empty, and so are those of the steps above it, which continued on that thread too. The wall-clock time is always measured. On the row of the totals, the three columns hold the sums over all steps, which add up to the figures of the explained statement. Available from release 28.0 and the beta release 27.1 before it.- One column per counter, counted by the step itself and not by the steps below it.
PLAN_BUILDScounts the execution plans built, also those of a subquery that is planned again for every row.EXPRESSION_CACHE_HITSandEXPRESSION_CACHE_MISSEScount the expressions found in or added to the cache of compiled expressions.JOINS_BY_COLUMN_INDEX,JOINS_BY_EXPRESSION_INDEXandJOINS_BY_NESTED_LOOPcount the algorithm a join chose.PAIRS_EVALUATEDcounts the combinations of rows on which a join evaluated its condition.ROWS_SORTEDcounts the rows a sort put in order.JOIN_ORDERS_CHOSEN_BY_ESTIMATEcounts the blocks of joins the cost model joined in another order than written,JOIN_KEY_SETS_PUSHEDthe joins which handed the distinct values of their left side to their right side as a filter, andROW_CAPS_BEHIND_FILTERthe reads of a table which handed the number of rows of alimitto the data container together with the conditions of thewhereclause. The other counters describe details of joins, of correlated subqueries and of layers which hand on their rows unchanged.
For explain, the columns that are only known after execution are empty.
Invantive Data Hub prints the answer of explain and explain analyze as a tree of the steps instead of a table, with per step only the figures that are known. describe shows the columns of a select without executing it.
Cost model
Where the data containers declare the number of rows of their tables, Invantive UniversalSQL uses these declarations to plan a statement:
- A block of inner joins and comma joins over tables is joined in the order which is estimated to read the fewest rows, for example the small table first and the large table last, so that the values of the small table narrow down the large one. The conditions of the
whereclause count as well as those of theonclauses, and a column without an alias belongs to the one table of the block with a column of that name. With anorder by, or when the select list holds onlycount,minandmax, the block is joined in another order when that is estimated to cost at most half. Otherwise it is joined in another order only when that is estimated to cost at most a hundredth and to answer at most 100,000 rows, and its rows are then put back in the order of thefromclause, so that the answer and the order of its rows stay the same. A block with an outer join, a grouping,distinct on, alimit, a table function or a join hint is joined as written. Rows with equal values for theorder bymay come in another order than before. - The search for the order starts with the order that each time adds the table which gives the fewest joined rows, and then looks for a cheaper one among at most 5,000 orders by default, abandoning an order as soon as it costs more than the best one found. A block of more than 64 tables is joined as written.
- A join hands up to half the estimated rows of a large right side, and at most 100,000 values, of its left side to the right side as a filter, instead of at most 10,000 values. A
join_setorno_join_sethint for the join, and the settingSQL_JOIN_SET_MAX_NUMBER_ROWS, take precedence. - A
limitbelow awhereclause is handed to the data container together with the conditions, when the wholewhereclause consists of conditions the data container receives and the data container declares that it then applies every condition exactly before the limit, or ignores the limit.
A driver which declares nothing is planned as before. The runtime settings Invantive.Sql.V1.CostModel switch the cost model off for an incident: JoinOrderEnabled, JoinSetEnabled and RowCapEnabled, each true by default. JoinOrderMaximumOrders, 5000 by default, is the most orders the search considers; 0 keeps the first order it makes. They are the section Invantive of the configProperties of runtimeconfig.json and are read when the process starts.
Measuring the exclusive figures costs a reading of the processor time per row per step. It is only done for explain analyze; a statement that is not explained is not measured. The same step statistics, one line of JSON per step, are written by Invantive Data Hub with /steps and returned by the tool analyze_records of Invantive MCP Server.
The same figures are available afterwards for every retained statement in SystemSqlExecutionSteps@DataDictionary, in the columns KIND, ALGORITHM, ESTIMATED_ROWS and COUNTERS.
Simplification
Before a statement is planned, Invantive UniversalSQL simplifies its conditions and joins. The answer stays the same; the plan shown by explain can differ from the statement as written:
- A condition which can never hold, such as
x = 1 and x = 2, is replaced byfalse, and a condition which always holds is left out. - A condition with a function on a column is rewritten into a condition on the column itself where the answer is the same, so that the data container can apply it. For example
trunc(d) = to_date('20261001', 'YYYYMMDD')is handed on as a range ond,nvl(c, 0) = 5on a mandatory columncasc = 5, andx * 2 > 10asx > 5. - A
left,rightorfullouter join is executed as an inner join when thewhereclause removes the rows without a match anyway, such aswhere b.amount > 0afterleft join b. The same holds for a condition in thewhereclause of a query on a view with such a join. Aleft joinover a foreign key on mandatory columns that are not texts is executed as an inner join as well, since every row has a match. - A
left joinof which no column is used is left out when its condition covers a unique key of the joined table, so that every row has at most one match. An inner join of which no column is used is left out when its condition follows a foreign key to a primary or unique key; a filter that the columns of the foreign key have a value takes its place. The table is then not read. - An
exists,not existsor correlatedinwhose subquery reads only the table a foreign key refers to, and only compares the columns of the foreign key with the columns they refer to, is answered by whether the columns of the foreign key have a value. The table of the subquery is then not read. For examplewhere exists (select 1 from customers c where c.id = o.customer_id)becomeswhere o.customer_id is not null. count(c)of a value that is never null counts every row, ascount(*)does;sum,minandmaxof a constant are calculated without reading every row.case when p then q end, and the same case compared withtrue, isp and qin awhereoronclause, so that both conditions can be handed to the data container. Not in a select list or under anot, where the case answers unknown and theandfalse.- A
distinctover one table is left out when the select list holds every column of a key that the platform guarantees and that is never null, or thewhereclause fixes such a column to a constant: the rows are distinct already. - A term of an
order byis left out when thewhereclause fixes its column to a constant, as inwhere a.id = 5 order by a.id, except for a text, of which'a'and'a 'are equal for the condition but sort apart; and for one table every term after the terms that hold such a key is left out. When no term is left, the rows are not sorted, and alimitcan be handed further down. - Conditions that every part of an
orshares are taken out of it in awhereoronclause:(a = 1 and b = 2) or (a = 1 and c = 3)isa = 1 and (b = 2 or c = 3), so thata = 1can be handed to the data container. - Two ranges of one numeric or date column that overlap or meet become one:
x between 1 and 5 or x between 4 and 9isx between 1 and 9, and for integers alsox between 1 and 5 or x between 6 and 9. A range of integers without an integer in it, such asx > 5 and x < 6, isfalse. Values of aninlist inside a range, and for integers next to it, join the range:x in (1, 2) or x between 2 and 4isx between 1 and 4, andx in (1, 2, 7) or x between 3 and 5isx between 1 and 5 or x = 7. Anot inkeeps only the values outside the range. A list withnullin it is left as it is. - The same holds over joins: a
left joinorjoinwhoseonclause compares every column of a key of the joined table that the platform guarantees with a constant or with a column of a table before it meets at most one row, so a key of the first table in the select list, or in theorder by, tells the rows apart:select distinct o.id, c.name from orders o join customers c on c.id = o.customer_idis not de-duplicated. - A
group bywithout aggregates whose columns, or the columns thewhereclause fixes, hold such a key is left out: every group is one row. The check that the select list reads only columns grouped by still runs first. With aggregates over such a key, each row is answered as a group of its own as it is read, without collecting all rows first, when every aggregate is acount,sum,min,maxoravgwithoutdistinct:count(*)is 1, and the others are the value of the row in the data type of the aggregate. Other aggregates, such aslistaggandstddev, keep the grouping. - Outside a
whereoronclause, rules that only keep the rows that are true, such asx = 1 and x = 2asfalse, are not applied when a column may be null: there the outcome is null, not false. - A call of a procedural SQL function with constant arguments is evaluated once, when the function consists only of calculations without SQL, loops or procedures.
Join elimination only relies on keys which the platform guarantees. The keys and their guarantee are shown in SystemTableKeys@DataDictionary and SystemTableForeignKeys@DataDictionary. A key with guarantee Declared is shown, but not relied upon. A foreign key read from the catalog of SQL Server, PostgreSQL or Oracle is guaranteed only when the database checks it for every row a query can read: it is enabled and validated, it cannot be deferred, and the table it refers to has no row level security. A text column of the foreign key also needs a collation that compares exactly: a binary collation such as Latin1_General_BIN2 on SQL Server, BINARY or USING_NLS_COMP on Oracle, and a deterministic collation on PostgreSQL. On Oracle and PostgreSQL a key of text is relied upon on the requirement that no two values of the key differ in trailing blanks only. The foreign keys of MySQL and MariaDB are only declared, since a session can turn their checks off.
The runtime settings Invantive.Sql.V1.ExpressionSimplification switch the simplification off for an incident: Enabled, true by default, switches off all rules, and RuleGroups switches off a group of rules by name, such as { "join-elimination": false }. The groups are contradiction, redundancy, tautology, or-union, same-text, arithmetic, function-range, function-identity, nvl, like, in-list, case, date-range, type-range, move-constant, boolean, transitivity, nullability, outer-join, join-elimination, sargable, psql-fold, semi-join, subquery, aggregate, distinct, order-by, factoring, range and group-by. They are read when the process starts, like the settings of the cost model. Available from release 28.0 and the beta release 27.1 before it.
Examples
The following example shows the plan of a join on two tables of the data dictionary. The join is planned as an index join, since its condition is an equality of two columns:
explain
select pkg.package_name
, fct.function_name
from systempackages@datadictionary pkg
join systempackagefunctions@datadictionary fct
on fct.package_name = pkg.package_name
STEP_ID PARENT_STEP_ID DEPTH KIND OPERATION ALIAS ALGORITHM
------- -------------- ----- ----------------- ------------------------------------------------------ ----- ---------------------
1 0 Statement Explained statement
2 1 1 Projection Select columns
3 2 2 Projection Column chaining into wider list
4 3 3 Join Inner join by index join on columns
5 4 4 DataContainerRead Data container I/O on 'PKG' (SYSTEMPACKAGES) PKG
6 4 4 DataContainerRead Data container I/O on 'FCT' (SYSTEMPACKAGEFUNCTIONS) FCT
The following example executes a join whose condition is not an equality, and shows the steps with the rows and the number of pairs evaluated. The figures depend on the release:
explain analyze
select pkg.package_name
, count(*)
from systempackages@datadictionary pkg
join systempackagefunctions@datadictionary fct
on fct.package_name < pkg.package_name
group
by pkg.package_name
order
by pkg.package_name
limit 3
STEP_ID KIND OPERATION ALGORITHM ROWS_IN ROWS_OUT PAIRS_EVALUATED ROWS_SORTED
------- ----------------- ----------------------------------------------------- ----------------------------------------- ------- -------- --------------- -----------
1 Statement Explained statement 3 0 0
2 ResultSet Data container I/O on '' 3 3 0 0
3 Top Top 3 3 0 0
4 ResultSet Data container I/O on '' 3 3 0 0
5 Sort Order by 3 3 0 18
6 Projection Select columns combined 18 18 0 0
7 GroupBy Group by 2295 18 0 0
8 Projection Column chaining into wider list 2295 2295 0 0
9 Join Inner join by nested loop: no equality of the two sides 150 2295 3689 0
10 DataContainerRead Data container I/O on 'FCT' (SYSTEMPACKAGEFUNCTIONS) 119 119 0 0
11 DataContainerRead Data container I/O on 'PKG' (SYSTEMPACKAGES) 31 31 0 0
Total Total of the statement 150 3 3689 18