search
HomeDatabaseMysql TutorialOracle sql 调优:使用虚拟索引在生产环境测试创建索引对数据库

虚拟索引是一种“假”索引,其定义存在于数据字典中,但不具有相应的索引段,也就是不会分配任何存储空间。利用虚拟索引,开发人员 可以无需等待索引创建完成,也不需要额外的索引存储空间,就可以当做索引已经存在,累测试 SQL 语句的执行计划。如果优化器

虚拟索引是一种“假”索引,其定义存在于数据字典中,但不具有相应的索引段,也就是不会分配任何存储空间。利用虚拟索引,开发人员
可以无需等待索引创建完成,也不需要额外的索引存储空间,就可以当做索引已经存在,累测试 SQL 语句的执行计划。如果优化器为某个
SQL 语句创建的执行计划代价很高,SQL tuning advisor 可能会建议在某个列上创建索引,但是在生产环境下,我们是没法随意
来创建索引和测试这些更改的。我们需要确保要创建的索引不会对数据库中运行的其他查询的执行计划产生任何影响。虚拟索引的出现就
是为了解决这个问题的:

下面我们来做一个测试来介绍虚拟索引的用法

1)  创建示例表

SQL> create table test as select * from dba_objects;

2) 对该表执行任意的查询

16:43:55 system@PROD>  select * from test where object_name = 'EMP';

OWNER                          OBJECT_NAME          SUBOBJECT_NAME                  OBJECT_ID DATA_OBJECT_ID OBJECT_TYPE         CREATED         LAST_DDL_TIME       TIMESTAMP           STATUS  T G S  NAMESPACE EDITION_NAME
------------------------------ -------------------- ------------------------------ ---------- -------------- ------------------- ------------------- ------------------- ------------------- ------- - - - ---------- ------------------------------
SCOTT                          EMP                                                      75315          75315 TABLE               2011-09-18 18:03:42 2013-03-10 17:07:42 2011-09-18:18:03:42 VALID   N N N      1

3) 查看上述查询的执行计划

16:44:31 system@PROD> set autotrace traceonly explain
16:44:42 system@PROD> select * from test where object_name = 'EMP';
Elapsed: 00:00:00.01

Execution Plan
----------------------------------------------------------
Plan hash value: 1357081020

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |    12 |  2484 |   293   (1)| 00:00:04 |
|*  1 |  TABLE ACCESS FULL| TEST |    12 |  2484 |   293   (1)| 00:00:04 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("OBJECT_NAME"='EMP')


Note
-----
   - dynamic sampling used for this statement (level=2)



4)  在 test 表的 object_name 字段上面创建虚拟索引

16:45:44 system@PROD> create index test_index on test(object_name) nosegment;

Index created.

注意,在创建虚拟索引时需要在 CREATE INDEX 语句中指定 nosegment 子句,执行上述语句后,实际上数据库中
并未创建索引段,也就是并未给 test_index 对象分配存储空间,这点我们可以通过下面步骤来验证。

5)  通过 dba_objects 可以查看到刚刚创建的 test_index 对象

16:46:02 system@PROD> set autotrace off

16:50:16 system@PROD> col object_name for a20;
16:50:26 system@PROD> select object_name,object_type from dba_objects where object_name = 'TEST_INDEX';

OBJECT_NAME          OBJECT_TYPE
-------------------- -------------------
TEST_INDEX           INDEX

但是通过 dba_indexes、dba_segments 和 dba_extents 我们查看不到该对象

16:53:06 system@PROD> select index_name,index_type,table_name from dba_indexes where index_name = 'TEST_INDEX';

no rows selected

16:55:50 system@PROD> select SEGMENT_NAME,SEGMENT_TYPE,TABLESPACE_NAME from dba_segments where segment_name = 'TEST_INDEX';

no rows selected

16:56:46 system@PROD> select SEGMENT_NAME,SEGMENT_TYPE,TABLESPACE_NAME from dba_extents where segment_name = 'TEST_INDEX';

no rows selected

通过上述的查询可以看出,数据库中创建了该对象,但未创建相应的 segment ,分配存储空间。

6)  再次查看之前 sql 的执行计划,看看是否使用了刚刚创建的虚拟索引

16:57:11 system@PROD> set autotrace traceonly explain
16:58:47 system@PROD> select * from test where object_name = 'EMP';
Elapsed: 00:00:00.04

Execution Plan
----------------------------------------------------------
Plan hash value: 1357081020

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |    12 |  2484 |   293   (1)| 00:00:04 |
|*  1 |  TABLE ACCESS FULL| TEST |    12 |  2484 |   293   (1)| 00:00:04 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("OBJECT_NAME"='EMP')

Note
-----
   - dynamic sampling used for this statement (level=2)

--我们看到创建虚拟索引后,执行计划并未改变

7)  我们需要修改数据库的隐含参数 _USE_NOSEGMENT_INDEXES 来强制session使用虚拟索引


17:01:24 system@PROD> alter session set "_USE_NOSEGMENT_INDEXES"=true;

Session altered.

8) 再次查看执行计划

17:02:06 system@PROD> select * from test where object_name = 'EMP';
Elapsed: 00:00:00.02

Execution Plan
----------------------------------------------------------
Plan hash value: 2627321457

------------------------------------------------------------------------------------------
| Id  | Operation                   | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |            |    12 |  2484 |     5   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| TEST       |    12 |  2484 |     5   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | TEST_INDEX |   309 |       |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------------------


Predicate Information (identified by operation id):
---------------------------------------------------


   2 - access("OBJECT_NAME"='EMP')


Note
-----
   - dynamic sampling used for this statement (level=2)
-----------------------------------------------------------------------------------------

设置 _USE_NOSEGMENT_INDEXES 隐含参数后,优化器将使用在此表上创建的虚拟索引。在其他session中运行该查询时,不会使用
此虚拟索引,因为我们只是修改了 session 级别的隐含参数。


虚拟索引使用的注意事项:

1、可以对虚拟索引执行 analyze 操作

17:07:13 system@PROD> analyze index TEST_INDEX compute statistics;

Index analyzed.

2、无法对虚拟索引执行 rebuild 操作,否则会报 ORA-8114: "User attempted to alter a fake index" 错误

17:07:52 system@PROD> alter index TEST_INDEX rebuild;
alter index TEST_INDEX rebuild
*
ERROR at line 1:
ORA-08114: can not alter a fake index

3、可以像普通索引那样删除虚拟索引

17:19:20 system@PROD> drop index test_index;

Index dropped.

4、在Oracle 9.2 to 11.1 中利用 DBMS_METADATA.get_ddl 来获取虚拟索引的 DDL 脚本时,不会输出虚拟索引的 nosegment 子句
我个人测试的环境是 11.2.0.3.5 可以输出 nosegment 子句

17:13:46 system@PROD>  select dbms_metadata.get_ddl('INDEX','TEST_INDEX','SYSTEM') DDL from dual;


DDL
--------------------------------------------------------------------------------


  CREATE INDEX "SYSTEM"."TEST_INDEX" ON "SYSTEM"."TEST" ("O
BJECT_NAME")

  PCTFREE 10 INITRANS 2 MAXTRANS 255  NOSEGMENT


http://blog.csdn.net/xiangsir/article/details/8693814

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 stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool