OceanBase Database uses the CREATE OUTLINE statement to bind an SQL statement to a specific execution plan, ensuring that the SQL always uses the specified plan in subsequent executions and avoiding performance fluctuations caused by improper optimizer choices. The CREATE OUTLINE statement supports the following plan binding modes:
- Exact binding: Binds an SQL statement to a specific execution plan on a one-to-one basis. This mode is suitable for single-database, single-table tuning scenarios.
- Template binding: Templates an outline using the
BINDING_RULEclause, making it effective for multiple SQL statements that match the pattern (such as similar SQL statements in database or table sharding scenarios). This mode is suitable for database or table sharding, SaaS multi-tenancy, and other scenarios.
For existing services, if the plan selected by the optimizer is not optimal, you can perform plan binding online. This means you do not need to modify the SQL; instead, you use DDL operations to add a set of hints to the SQL. The optimizer then generates a better plan for the SQL based on these specified hints. This set of hints is called an outline.
Outline view
The outline view is named DBA_OB_OUTLINES, and its columns are described in the following table.
Field |
Type (MySQL-compatible mode) |
Type (Oracle-compatible mode) |
Description |
|---|---|---|---|
| CREATE_TIME | TIMESTAMP(6) | TIMESTAMP(6) | Creation Timestamp |
| MODIFY_TIME | TIMESTAMP(6) | TIMESTAMP(6) | Modified Timestamp |
| TENANT_ID | BIGINT(20) | NUMBER(38) | Tenant ID |
| DATABASE_ID | BIGINT(20) | NUMBER(38) | Database ID |
| OUTLINE_ID | BIGINT(20) | NUMBER(38) | Outline ID |
| DATABASE_NAME | VARCHAR2(128) | VARCHAR2(128) | Database Name |
| OUTLINE_NAME | VARCHAR2(128) | VARCHAR2(128) | Outline Name |
| VISIBLE_SIGNATURE | LONGTEXT | CLOB | The deserialized result of the Signature, for easy viewing of Signature information. |
| SQL_TEXT | LONGTEXT | CLOB | The SQL statement specified in the ON clause when creating an outline. |
| OUTLINE_TARGET | LONGTEXT | CLOB | The SQL statement specified in the TO clause when creating an outline. |
| OUTLINE_SQL | LONGTEXT | CLOB | SQL with complete outline information |
| SQL_ID | VARCHAR2(32) | VARCHAR2(32) | SQL identifiers |
| OUTLINE_CONTENT | LONGTEXT | CLOB | Complete execution plan outline information |
| PATTERN_RULES | LONGTEXT | CLOB | The MAP rules of the template outline, stored in JSON format. If this field is not empty, it indicates a template outline; if empty, it indicates an exact outline. |
Precise binding
Precise binding is a native plan binding capability of OceanBase Database. It binds an SQL statement to a specific execution plan on a one-to-one basis using SQL_TEXT or SQL_ID. The behavior of an Outline row without BINDING_RULE is identical to previous versions.
Create an Outline using SQL_TEXT
When you create an Outline using SQL_TEXT, a Key-Value pair is generated and stored in a Map. The Key is the parameterized text of the bound SQL, and the Value is the bound Hint. For specific parameterization principles, see Quick parameterization.
The syntax for creating an Outline using SQL_TEXT is as follows:
CREATE [OR REPLACE] OUTLINE <outline_name> ON <stmt> [ TO <target_stmt> ];
Explanation:
Specifying
OR REPLACEallows you to replace an existing execution plan.stmtis typically a DML statement with hints and original parameters.If
TO target_stmtis not specified, it means that if the SQL passed to the database after parameterization matches the SQL instmtwithout hints, this SQL will be bound to the execution plan generated by the hints instmt.To ensure a fixed plan is executed for statements containing hints, you need
TO target_stmtto specify the original SQL.Example:
obclient> CREATE OUTLINE outline1 ON SELECT /*+NO_REWRITE*/ * FROM tbl1 WHERE col1 = 4 AND col2 = 6 ORDER BY 2 TO SELECT * FROM tbl1 WHERE col1 = 4 AND col2 = 6 ORDER BY 2;Note
When using
target_stmt,stmtandtarget_stmtmust match exactly after removing hints.
In the following example, the optimizer chooses to perform a primary key scan. If the data volume increases, executing the index idx_c2 would be a more optimized choice for this SQL. In this case, you can create an Outline to bind this SQL to the index plan and execute it.
obclient> CREATE TABLE t1 (c1 INT PRIMARY KEY, c2 INT, c3 INT, INDEX idx_c2(c2));
Query OK, 0 rows affected
obclient> INSERT INTO t1 VALUES(1, 1, 1), (2, 2, 2), (3, 3, 3);
Query OK, 1 rows affected
obclient> EXPLAIN SELECT * FROM t1 WHERE c2 = 1;
Query Plan:
===================================
|ID|OPERATOR |NAME|EST. ROWS|COST|
-----------------------------------
|0 |TABLE SCAN|t1 |1 |37 |
===================================
Outputs & filters:
-------------------------------------
0 - output([t1.c1], [t1.c2], [t1.c3]), filter([t1.c2 = 1]),
access([t1.c2], [t1.c1], [t1.c3]), partitions(p0)
Create an Outline based on the following SQL statement:
obclient> CREATE OUTLINE otl_idx_c2
ON SELECT/*+ INDEX(t1 idx_c2)*/ * FROM t1 WHERE c2 = 1;
Query OK, 0 rows affected
Create an Outline using SQL_ID
The syntax for creating an Outline using SQL_ID is as follows:
obclient> CREATE OUTLINE outline_name ON sql_id USING HINT hint_text;
SQL_ID is the SQL_ID corresponding to the SQL statement to be bound. You can obtain it in the following ways:
Query
V$OB_PLAN_CACHE_PLAN_STAT.Query
GV$OB_SQL_AUDIT.Generate an
SQL_IDusing MD5 for a parameterized original SQL statement. You can refer to the following script to generate theSQL_IDfor the corresponding SQL.IMPORT hashlib sql_text='SELECT * FROM t1 WHERE c2 = ?' sql_id=hashlib.md5(sql_text.encode('utf-8')).hexdigest().upper() PRINT(sql_id)
Use the SQL_ID to bind an outline, as shown in the following example:
obclient> CREATE OUTLINE otl_idx_c2 ON 'ED570339F2C856BA96008A29EDF04C74'
USING HINT /*+ INDEX(t1 idx_c2)*/ ;
Notice
- The hint format is
/*+ xxx */. For detailed information about hints, see Optimizer Hint. - An outline created by using the
SQL_TEXTmethod will overwrite an outline created by using theSQL_IDmethod. TheSQL_TEXTmethod has a higher priority. - If the SQL statement corresponding to
SQL_IDalready has hints, creating an outline with specified hints will overwrite all hints in the original statement.
Outline Data
Outline Data is a set of hint information generated by the optimizer to fully reproduce a plan. It begins with BEGIN_OUTLINE_DATA and ends with END_OUTLINE_DATA.
You can obtain Outline Data using the EXPLAIN EXTENDED command, as shown in the following example:
obclient> EXPLAIN EXTENDED SELECT/*+ index(t1 idx_c2)*/ * FROM t1 WHERE c2 = 1;
Query Plan:
| =========================================
|ID|OPERATOR |NAME |EST. ROWS|COST|
-----------------------------------------
|0 |TABLE SCAN|t1(idx_c2)|1 |88 |
=========================================
Outputs & filters:
-------------------------------------
0 - output([t1.c1(0x7ff95ab37448)], [t1.c2(0x7ff95ab33090)], [t1.c3(0x7ff95ab377f0)]), filter(nil),
access([t1.c2(0x7ff95ab33090)], [t1.c1(0x7ff95ab37448)], [t1.c3(0x7ff95ab377f0)]), partitions(p0),
is_index_back=true,
range_key([t1.c2(0x7ff95ab33090)], [t1.c1(0x7ff95ab37448)]), range(1,MIN ; 1,MAX),
range_cond([t1.c2(0x7ff95ab33090) = 1(0x7ff95ab309f0)])
Used Hint:
-------------------------------------
/*+
INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2")
*/
Outline Data:
-------------------------------------
/*+
BEGIN_OUTLINE_DATA
INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2")
END_OUTLINE_DATA
*/
Plan Type:
-------------------------------------
LOCAL
Optimization Info:
-------------------------------------
t1:table_rows:3, physical_range_rows:1, logical_range_rows:1, index_back_rows:1, output_rows:1, est_method:local_storage, optimization_method=cost_based, avaiable_index_name[idx_c2], pruned_index_name[t1]
level 0:
***********
paths(@1101710651081553(ordering([t1.c2], [t1.c1]), cost=87.951827))
The Outline Data information is as follows:
/*+
BEGIN_OUTLINE_DATA
INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2")
END_OUTLINE_DATA
*/
Outline Data is also a type of hint and can therefore be used during plan binding, as shown in the following example:
obclient> CREATE OUTLINE otl_idx_c2
ON 'ED570339F2C856BA96008A29EDF04C74'
USING HINT /*+
BEGIN_OUTLINE_DATA
INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2")
END_OUTLINE_DATA
*/;
Query OK, 0 rows affected
Template binding
Template binding is a new plan binding capability in OceanBase Database. It uses the BINDING_RULE clause to template an Outline, making it effective for multiple SQL statements that match the pattern. This is suitable for scenarios such as database and table sharding, or SaaS multi-tenancy, where data of the same model is distributed across multiple tables or databases.
BINDING_RULE syntax
The syntax for creating a template Outline is as follows:
CREATE [OR REPLACE] OUTLINE outline_name ON stmt
BINDING_RULE (binding_item);
binding_item:
SCOPE = {DATABASE | TENANT}
| MAP = {real_name TO 'pattern', ...}
The parameters are described as follows:
OR REPLACE: Optional. When specified, existing execution plans will be replaced.outline_name: Specifies the name of the Outline to be created.stmt: Typically a DML statement with hints and original parameters.BINDING_RULE (binding_item): Used to specify the scope of this Outline.Note
For V4.4.2, the
BINDING_RULEclause was introduced starting from V4.4.2 BP3.SCOPE = {DATABASE | TENANT}:SCOPE = DATABASE: The default value, meaning it only takes effect in the current database.SCOPE = TENANT: Meaning it takes effect in all databases under the current tenant.
MAP = {real_name TO 'pattern', ...}: Specifies the wildcard rules for table names/database names. The left side is the actual table name ordb.tableformat, and the right side ispattern.patterncan contain${variable_name}or${variable_name:regex}.Notice
${var}or${var:regex}: Defines a variable namedvar, with an optional regular expression. If no regex is specified, it matches any non-empty string by default.- When the left side of
MAPis in thedb.tableformat, the right-sidepatternmust be split into two groups of single quotes:'db_pattern'.'table_pattern'. - In the same
BINDING_RULE, variables must be defined before being referenced, and variables with the same name must have consistent values across all references.
Four typical binding modes
Mode |
SCOPE |
MAP |
Application scenarios |
|---|---|---|---|
| Exact binding | DATABASE (default) | empty | Single database and single table (original behavior) |
| Current Database Wildcard Sharded Table | DATABASE | Wildcard for Table Name Only | Within a single databaseorders_001 … orders_127Partitioned tables |
| Cross-Database Exact Table Name | TENANT | empty | For tables with the same name across multiple databases, for example,db_001.orders、db_002.orders |
| Cross-database wildcard | TENANT | Includingdb.tablewildcard |
Compound wildcard for database name and table name |
Cross-database binding for tables with the same name
In a database sharding architecture, there may be tables with the same name across multiple shards (for example, db_001.orders and db_002.orders). Using SCOPE = TENANT allows one Outline to cover all tables with the same name across all shards.
Example:
The orders table in all databases uses the idx_status index:
obclient> CREATE OUTLINE otl_orders
ON SELECT /*+ index(orders, idx_status) */*
FROM orders
WHERE status = 'a'
BINDING_RULE (SCOPE = TENANT);
Example of a query hit in database
db_001.obclient> USE db_001;obclient> SELECT * FROM orders WHERE status = 'pending';Example of a query hit in database
db_002.obclient> USE db_002;obclient> SELECT * FROM orders WHERE status = 'pending';Example of a query hit in database
db_test.obclient> USE db_test;obclient> SELECT * FROM orders WHERE status = 'pending';
Wildcard for current database's sharded tables
In a sharded table architecture, a single database contains multiple sharded tables with a consistent naming pattern (for example, orders_sh, orders_hz, orders_bj). Using MAP with regular expression variables allows you to cover all sharded tables with a single outline.
Example:
The orders_xx series of sharded tables share the same outline:
obclient> CREATE OUTLINE otl_orders_tpl
ON SELECT /*+ index(orders_sh, idx_status) */*
FROM orders_sh
WHERE status = 'a'
BINDING_RULE (MAP = {orders_sh TO 'orders_${S:[a-z]+}'});
Example of a query hit where
S=bj.obclient> SELECT * FROM orders_bj WHERE status = 'pending';Example of a query hit where
S=hz.obclient> SELECT * FROM orders_hz WHERE status = 'pending';Example of a non-hit query, as
001does not match[a-z]+.obclient> SELECT * FROM orders_001 WHERE status = 'pending';
Combined wildcard for database name and table name
In an architecture with combined database and table sharding (for example, db_001.orders_sh, db_002.orders_bj), you can use wildcards for both the database name and table name.
Example:
Effective only for databases in the db_numeric pattern + tables in the orders_alpha pattern:
obclient> CREATE OUTLINE otl_full
ON SELECT *
FROM db_001.orders_sh
WHERE status = 'a'
BINDING_RULE (
SCOPE = TENANT,
MAP = {db_001.orders_sh TO 'db_${D:[0-9]+}'.'orders_${S:[a-z]+}'}
);
Example of a hit query.
obclient> SELECT * FROM db_002.orders_bj WHERE status = 'pending';Example of a miss query, where the database name does not match.
obclient> SELECT * FROM test_db.orders_sh WHERE status = 'pending';
To cover all tables under a specific database, you can use the wildcard regular expression ${T:.*}:
obclient> CREATE OUTLINE otl_db_all
ON SELECT *
FROM db_001.orders
WHERE status = 'a'
BINDING_RULE (
SCOPE = TENANT,
MAP = {db_001.orders TO 'db_${D:[0-9]+}'.'${T:.*}'}
);
Multi-table JOIN and variable consistency constraints
In multi-table JOIN scenarios, if all tables involved in the JOIN are sharded tables, you must ensure that the same variable has consistent values across all references to avoid incorrect table combination matching (for example, orders_hz JOIN products_bj).
Using the same variable name within the same MAP implements the consistency constraint.
Example:
The S in orders_${S} and products_${S} must be the same.
obclient> CREATE OUTLINE otl_join
ON SELECT /*+ use_nl(orders_sh) */o.*, p.*
FROM orders_sh o JOIN products_sh p
ON o.id = p.order_id
BINDING_RULE (
MAP = {
orders_sh TO 'orders_${S:[a-z]+}',
products_sh TO 'products_${S}'
}
);
Example of a hit query, where
S=hz,orders_hz JOIN products_hz.obclient> SELECT o.*, p.* FROM orders_hz o JOIN products_hz p ON o.id = p.order_id;Example of a miss query, where
S=hzforordersandS=bjforproducts. The variables are inconsistent, so the query automatically misses.obclient> SELECT o.*, p.* FROM orders_hz o JOIN products_bj p ON o.id = p.order_id;
Scope and matching priority
Scope
DATABASE(default): The outline takes effect only in the current database. The database where the outline is created is the scope database.TENANT: The outline takes effect in all databases of the current tenant. You still need to executeCREATE OUTLINEin a certain database during creation, but the scope extends to the entire tenant.
Matching priority
When the same SQL statement may match multiple outlines, OceanBase Database matches them in descending order of priority as follows:
- Exact
signatureof the current database: exactly matches the parameterized text of the SQL statement. sql_idof the current database: an outline created bySQL_ID.format outline: an outline withTO target_stmt.- Current database template: a template outline with
SCOPE = DATABASE. - Cross-database (tenant) template: a template outline with
SCOPE = TENANT.
The current database template strictly takes precedence over the cross-database template, so ambiguity is avoided.
Verify that an outline is created and takes effect
You must verify whether the created outline is successful and meets expectations. The verification methods for precise outlines and template outlines are slightly different.
Verify a precise outline
To verify that a precise outline takes effect, perform the following three-step validation:
Confirm that the outline is successfully created.
Check the
DBA_OB_OUTLINESview to confirm whether the outline with the specified name has been successfully created.obclient> SELECT * FROM DBA_OB_OUTLINES WHERE OUTLINE_NAME = 'otl_idx_c2'\G *************************** 1. row *************************** tenant_id: 1001 database_id: 1100611139404776 outline_id: 1100611139404777 database_name: test outline_name: otl_idx_c2 visible_signature: SELECT * FROM t1 WHERE c2 = ? sql_text: SELECT/*+ index(t1 idx_c2)*/ * FROM t1 WHERE c2 = 1 outline_target: outline_sql: SELECT /*+ BEGIN_OUTLINE_DATA INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2") END_OUTLINE_DATA*/* FROM t1 WHERE c2 = 1Confirm that the new SQL generates a new execution plan using the bound outline.
When executing a query with SQL bound to an outline, query the
outline_idin the plan information corresponding to that SQL in theGV$OB_PLAN_CACHE_PLAN_STATtable. If theoutline_idmatches theoutline_idfound inDBA_OB_OUTLINES, it indicates the execution plan was generated according to the bound outline; otherwise, it was not.obclient> SELECT SQL_ID, PLAN_ID, STATEMENT, OUTLINE_ID, OUTLINE_DATA FROM oceanbase.GV$OB_PLAN_CACHE_PLAN_STAT WHERE STATEMENT LIKE '%SELECT * FROM t1 WHERE c2 =%'\G *************************** 1. row *************************** sql_id: ED570339F2C856BA96008A29EDF04C74 plan_id: 17225 statement: SELECT * FROM t1 WHERE c2 = ? outline_id: 1100611139404777 outline_data: /*+ BEGIN_OUTLINE_DATA INDEX(@"SEL$1" "test.t1"@"SEL$1" "idx_c2") END_OUTLINE_DATA*/Confirm that the generated execution plan meets expectations.
After confirming the plan was generated by the bound outline, verify whether the generated plan meets expectations. You can query the
GV$OB_PLAN_CACHE_PLAN_EXPLAINtable to check the shape of the cached execution plan inplan_cache. For specific viewing methods, refer toReal-time execution plan display.
obclient> SELECT OPERATOR, NAME FROM oceanbase.GV$OB_PLAN_CACHE_PLAN_EXPLAIN WHERE TENANT_ID = 1001 AND SVR_IP = '10.XXX.XXX.XXX' AND SVR_PORT = 30474 AND PLAN_ID = 17225; +--------------------+------------+ | OPERATOR | NAME | +--------------------+------------+ | PHY_ROOT_TRANSMIT | NULL | | PHY_TABLE_SCAN | t1(idx_c2) | +--------------------+------------+
Verify a template outline
The verification method for a template outline is similar to that for a precise outline, but note the following points:
Confirm that the template outline is successfully created.
Check the
pattern_rulesfield in theDBA_OB_OUTLINESview to confirm whether it is a template outline. A non-emptypattern_rulesfield indicates it is a template outline. To view all template outlines:obclient> SELECT outline_name, visible_signature, pattern_rules FROM oceanbase.DBA_OB_OUTLINES WHERE pattern_rules IS NOT NULL AND pattern_rules != '';Confirm whether the SQL hits the template outline.
After a template outline is hit, the
outline_idinGV$OB_PLAN_CACHE_PLAN_STATwill also be filled with theIDof the corresponding outline (outline_idgreater than 0 indicates a hit). Query to check if it hit:obclient> SELECT outline_id, outline_data FROM oceanbase.GV$OB_PLAN_CACHE_PLAN_STAT WHERE query_sql LIKE '%your_marker%' LIMIT 1;Multi-partition verification. For a template outline, it is recommended to use SQLs for different partitions to verify separately, ensuring all expected partitions correctly hit the template outline.
Delete an outline
After deleting an outline, the corresponding SQL will no longer regenerate an execution plan based on the bound outline.
The syntax for dropping an outline is as follows:
DROP OUTLINE outline_name
[BINDING_RULE (binding_item)];
binding_item:
SCOPE = {DATABASE | TENANT}
The parameters are described as follows:
outline_name: Specifies the name of the outline to be dropped.BINDING_RULE (binding_item): Optional. Specifies the scope for dropping the outline.BINDING_RULE (SCOPE = DATABASE): The default value. Drops the outline at the current database level (equivalent to not specifying theBINDING_RULEparameter).BINDING_RULE (SCOPE = TENANT): Drops a cross-database (tenant-level) outline with the specified name.
Note
For V4.4.2, the
BINDING_RULEclause is introduced starting from V4.4.2 BP3.
Note
- To drop a precise outline (
SCOPE = DATABASE), you must execute the statement in the corresponding database, or specify the database name inoutline_name. - To drop a cross-database outline (
SCOPE = TENANT), you can execute the statement in any database, but you must explicitly specifyBINDING_RULE(SCOPE = TENANT).
Relationship between plan binding and execution plan caching
After creating a precise outline using
SQL_TEXT, the key used by SQL requests to find the outline when generating a new plan is the same as the key used by the plan cache, which is the parameterized text string of the SQL.Template outlines use a template signature for candidate filtering, then verify whether a match occurs through a regular expression pattern. The additional overhead during the template matching phase mainly comes from AST-level template signature generation and regular expression verification.
When a precise outline is created or deleted, if the corresponding SQL receives a new request, it triggers the invalidation of the corresponding execution plan in the execution plan cache, updating it with the execution plan generated based on the bound outline.
When a template outline is created or deleted, the plan caches for all SQL statements that match this template pattern become invalid.
When an outline is created or deleted, if the corresponding SQL receives a new request, it triggers the invalidation of the corresponding execution plan in the execution plan cache, updating it with the execution plan generated based on the bound outline.
Performance impact
Scenarios |
Complexity |
Note |
|---|---|---|
| No template outline found in the system. | O(1) | Via the has_template_outline short-circuit switch skips the template matching path, so tenants without a template outline incur no additional overhead. |
| Exact Outline Hit | O(1) | Reuses the original hash matching, so the performance of exact binding is not affected by the template binding feature. |
| Template outline matched | O(1) hash + n × O(T) pattern verification | n: the number of candidate templates with the same signature; T: the number of tables in the SQL statement. |
| Variable Consistency Verification | O(V) | V: the number of variables, typically ≤ 3. |
Regular expressions are limited in length (≤128 characters) and have a timeout mechanism to prevent pathological regular expressions from slowing down matching.
Limitations and considerations
- When
MAPcontainsdb.tableformat, you must explicitly specifySCOPE = TENANT; otherwise, creation will fail. - Within the same
BINDING_RULE, each database namepatternand table namepatterncan have at most one variable. Complex expressions should be split into multiple outlines. - Variables must be defined before being referenced. A variable with the same name can only be defined once.
- The
db.*syntax is not supported. Please use equivalent expressions such as'db_${D:[0-9]+}'.'${T:.*}'. - Regular expressions use POSIX extended syntax and do not support complex features such as backreferences or zero-width assertions.
- Outlines with only
SCOPE = DATABASEand noMAPbehave exactly the same, equivalent to historical precise outlines. - The
MAX_CONCURRENTthrottling type outlines currently do not supportBINDING_RULE. - Cross-tenant outline binding is not supported.
References
The CREATE FORMAT OUTLINE statement also applies in the PS scenario, and its matching rules are consistent with those of the text protocol. For more information, see CREATE FORMAT OUTLINE (MySQL-compatible mode) and CREATE FORMAT OUTLINE (Oracle-compatible mode).