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
How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL Commands in MySQL: Practical ExamplesSQL Commands in MySQL: Practical ExamplesApr 14, 2025 am 12:09 AM

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

How does InnoDB handle ACID compliance?How does InnoDB handle ACID compliance?Apr 14, 2025 am 12:03 AM

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft