Drawbacks of plan caching
In the previous section, we mentioned that for a parameterized SQL statement, after generating an execution plan, it is saved to the plan cache. Subsequent executions of the same SQL will then reuse this plan. While this approach saves time on plan generation, it introduces a potential worst-case scenario in data skew scenarios. Let's illustrate this with an example.
Consider the following definition for table t1: assume column c1 has only two values, where value 0 accounts for 1% of all data and value 1 accounts for 99%; column c2 has 10 distinct values from 1 to 10, each accounting for 10%. For the SQL statement SELECT * FROM t1 WHERE c1 = ? AND c2 = ?, if the optimizer sees the condition c1 = 0 and c2 = 1 during plan generation, it will choose to use index idx1. It first retrieves 1% of the data that satisfies c1 = 0 from the index, then performs an index back-to-table scan to filter out data that does not meet the C2 = 1 condition, and returns the results. In this case, the query is completed by scanning 1% of the data plus an additional 1% for the index back-to-table scan. However, if the server later receives another SQL statement where the user-provided conditions become c1 = 1 and c2 = 1, reusing the previously generated plan would now involve first retrieving 99% of the data that satisfies C1 = 1 from index idx1, then performing an index back-to-table scan to filter out data that does not meet the C2 = 1 condition, and returning the results. This requires scanning 99% of the data plus an additional 99% for the index back-to-table scan to complete the query. Clearly, for this SQL statement, using index idx2 is a better choice because regardless of the values, using idx2 always requires scanning only 10% of the data plus a 10% back-to-table scan, making the SQL execution time more stable.
create table t1 (
c1 int,
c2 int,
c3 int,
key idx1 (c1),
key idx2 (c2)
);
When encountering this situation, users can bind an execution plan to the SQL using an outline (for database/sharding scenarios, one template outline can cover all shards without needing to create one for each). This forces the query request to use index idx2. Of course, there are actually better optimization methods for this SQL, but since they are not the focus of this topic, they will not be elaborated here.
Plan binding
Plan binding is a mechanism provided by OceanBase Database that allows users to control execution plans by creating outlines in the database, without modifying the SQL itself. OceanBase Database supports creating outlines in two ways: one is through SQL_TEXT (the original parameterized statement executed by the user), and the other is through SQL_ID.
Creating outlines in versions prior to V4.4.2 BP3 required entering the corresponding database to execute. For OceanBase Database V4.4.2, starting from V4.4.2 BP3, the BINDING_RULE clause was introduced to set the effective level of the outline. This feature has the following characteristics:
- Cross-database binding: One outline can apply to all tables with the same name within a tenant.
- Template binding: By using
${var:regex}to wildcard table or database names, one outline can cover any naming convention for database or table sharding. - Multi-table variable constraint: When joining multiple sharded tables with
JOIN, the same variable must have the same value to avoid incorrect matching. - Full backward compatibility: If
BINDING_RULEis not explicitly written, its behavior will be consistent with historical versions (prior to V4.4.2 BP3).
Create an outline using SQL_TEXT
When creating 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 binding hint. For specific parameterization rules, 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
| 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 can be replaced.outline_name: Specifies the name of the outline to be created.stmt: Typically a DML statement with hints and original parameters.TO target_stmt: If not specified, it means that if the SQL parameterized by the database matches the SQL instmtwithout hints, this SQL will be bound to the hints instmtto generate an execution plan. To ensure a fixed plan is executed for statements containing hints,TO target_stmtis needed to 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 the hints.BINDING_RULE (binding_item): Optional. Used to specify the effective level of this outline.Note
For V4.4.2, the
BINDING_RULEclause is introduced starting from V4.4.2 BP3.SCOPE = {DATABASE | TENANT}:SCOPE = DATABASE: The default value, which means it takes effect only in the current database.SCOPE = TENANT: It means it takes effect in all databases under the current tenant.
MAP = {real_name TO 'pattern', ...}: Applies thepatternon the right to the real table name ordb.tableon the left. Inpattern, you can write${variable name}or${variable name:regular expression}. For examples, see the Wildcard for Sharded Tables in the Current Database section below.Notice
- When the
MAPleft side is in thedb.tableform, 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. Variables with the same name must have consistent values across all references.
- When the
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 to be bound. You can obtain it in the following ways:
By querying
V$OB_PLAN_CACHE_PLAN_STAT.By querying
GV$OB_SQL_AUDIT.Generate the
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 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)*/ ;
Template binding in database and table sharding scenarios
Cross-database binding for tables with the same name
In a database sharding architecture, multiple shards may contain tables with the same name (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 the 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';
References
Besides using the SQL_TEXT and SQL_ID methods, you can also create fuzzy outlines using CREATE FORMAT OUTLINE for plan binding. This method is effective for both text and PS protocols. For more details, see CREATE FORMAT OUTLINE (MySQL-compatible mode) and CREATE FORMAT OUTLINE (Oracle-compatible mode).