search
HomeDatabaseMysql TutorialOracle约束Constraint对于CBO优化器的作用

进入CBO优化器时代之后,成本计算值决定执行计划的选取已经成为主流。一条性能良好的执行计划建立在尽可能ldquo;贴切rdquo;的统

进入CBO优化器时代之后,成本计算值决定执行计划的选取已经成为主流。一条性能良好的执行计划建立在尽可能“贴切”的统计量基础上。CBO内部又经历了两个时代——IO Cost和CPU Cost,两者的区别就在于系统统计量(System Statistical)的应用。
 
RBO时代,执行计划其实也是有评估的。RBO的执行计划评定级别不会像CBO成本粒度那么细,而是15个路径等级评定。等级编号低的执行计划比等级编号高的执行计划更会被选择到。
 
在这个过程中,我们其实还是忽略了影响执行计划的因素,就是约束(Constraint)。Constraint对于数据库对象很重要,所谓约束,就是建立在数据表、数据列上的规则限制。Constraint的存在目的就是将业务规则融入到数据表设计中。
 
Constraint确定描述了数据表的一些固有特性,比如非空、外键,就从一个程度上给出了数据表特性的描述。经常性的将Constraint作为一种数据完整性约束的实现,但是对于CBO而言,约束也是搜寻“捷径”执行计划的重要信息来源。从经验上看,约束能够给CBO带来的高效执行计划作用,是不可忽视的。
 
本篇介绍几个常见的业务场景,说明在合理规划约束的情况下,CBO能够生成更好地执行计划。

--------------------------------------分割线 --------------------------------------

 

相关阅读:

Oracle完整性约束

Oracle的约束和索引

从Oracle的约束到索引

Oracle常用数据类型和完整性约束

ORA-02291: 违反完整约束条件 …… - 未找到父项关键字

--------------------------------------分割线 --------------------------------------

1、执行环境介绍

 

我们同时要使用CBO和RBO进行测试过程,选择Oracle 11g进行测试。

 

SQL> select * from v$version;

 

BANNER

---------------------------------

Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - Production

PL/SQL Release 11.2.0.3.0 - Production

CORE 11.2.0.3.0 Production

TNS for Linux: Version 11.2.0.3.0 - Production

NLSRTL Version 11.2.0.3.0 – Production

 

当前默认使用CBO优化器组件。

 

SQL> show parameter optimizer

 

NAME                                TYPE        VALUE

------------------------------------ ----------- ------------------------------

optimizer_mode                      string      ALL_ROWS

optimizer_use_sql_plan_baselines    boolean    TRUE

(篇幅原因,有省略……)

 

2、“null还是not null”大不一样

 

我们在实际设计数据库中,经常会忽略字段非空设置。不少朋友和开发团队对于这个细节不以为然,认为这个设置就是会影响到插入过程。一些朋友认为:在应用层面验证一下就可以了。但是实际上,,null与not null,大不一样!有很多方面的差异和问题,纯应用层面验证是不能解决问题的。
 
笔者从性能优化器角度,介绍一下忽视not null效果的问题。我们首先创建实验数据表T。

 

--数据表T

SQL> create table t as select * from dba_objects;

Table created

 

--其他用途索引

SQL> create index idx_t_id on t(object_id);

Index created

 

--统计量收集

SQL> exec dbms_stats.gather_table_stats(user,'T',cascade => true);

PL/SQL procedure successfully completed

 

 

还是我们经常设置的场景,就是没有where条件的count动作。

 

 

SQL> explain plan for select count(*) from t;

 

Explained

 

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

 

PLAN_TABLE_OUTPUT

-----------------------------------------------------

Plan hash value: 2966233522

-------------------------------------------------

| Id  | Operation          | Name | Rows  | Cost (%CPU)| Time    |

-------------------------------------------------

|  0 | SELECT STATEMENT  |      |    1 |  294  (1)| 00:00:04 |

|  1 |  SORT AGGREGATE    |      |    1 |            |          |

|  2 |  TABLE ACCESS FULL| T    | 75609 |  294  (1)| 00:00:04 |

----------------------------------------------

 

9 rows selected

 

很正常的执行计划,因为需要检索所有的数据行记录,检索数据表所有的记录是比较直观的想法。这个FTS执行计划成本值294。我们修改一下索引列object_id的属性,将其从原先的null设置为not null。
 
 

 

SQL> alter table t modify object_id not null;

Table altered

 

SQL> explain plan for select count(*) from t;

Explained

 

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

 

PLAN_TABLE_OUTPUT

--------------------------------------------------------------------------------
 
Plan hash value: 3570898368

--------------------------------------------------------------------------

| Id  | Operation            | Name    | Rows  | Cost (%CPU)| Time    |

--------------------------------------------------------------------------

|  0 | SELECT STATEMENT      |          |    1 |    48  (3)| 00:00:01 |

|  1 |  SORT AGGREGATE      |          |    1 |            |          |

|  2 |  INDEX FAST FULL SCAN| IDX_T_ID | 75609 |    48  (3)| 00:00:01 |

--------------------------------------------------------------------------

 

9 rows selected

 

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use