Индексы ROWID — это объекты базы данных, обеспечивающие отображение всех значений столбца таблицы, а также идентификаторов ROWID всех строк таблицы, в которых содержатся значения столбца.
ROWID — это псевдостолбец, который является уникальным идентификатором строки в таблице и фактически описывает точное физическое расположение данной конкретной строки. На основе этой информации Oracle впоследствии может найти данные, связанные со строкой таблицы. При каждом перемещении, экспорте, импорте строки, а также при выполнении любых других операций, которые приводят к изменению ее местонахождения, изменяется ROWID строки, поскольку она занимает другое физическое положение. Для хранения данных ROWID требуется 80 бит (10 байт). Идентификаторы ROWID состоят из четырех компонентов: номера объекта (32 бита), относительного номера файла (10 бит), номера блока (22 бита) и номера строки (16 бит). Эти идентификаторы отображаются как 18-символьные последовательности, указывающие местонахождение данных в БД, причем каждый символ представлен в формате base-64, состоящем из символов A-Z, a-z, 0-9, + и /. Первые шесть символов – это номер объекта данных, следующие три – относительный номер файла, следующие шесть – номер блока, последние три – номер строки.
Пример:
SELECT fam, ROWID FROM student;
В базе данных Oracle индексы используются для разных целей: для обеспечения уникальности значений в базе данных, для повышения производительности поиска записей в таблице и др. Производительность повышается благодаря тому, что в критерии поиска данных в таблице включается ссылка на индексированный столбец или столбцы. В Oracle индексы можно создавать по любому столбцу таблицы, кроме столбцов типа LONG. Индексы проводят различие между приложениями, для которых скорость не важна, и интенсивно функционирующими приложениями, что особенно касается работы с большими таблицами. Однако, прежде чем принять решение о создании индекса, необходимо взвесить все «за» и «против» в отношении производительности системы. Производительность не повысится, если просто ввести индекс и забыть о нем.
Рекомендации по созданию индексов ROWID:
Хотя наибольшее повышение производительности достигается созданием индекса по столбцу, все значения которого уникальны, похожий результат можно получить и для столбцов, содержащих одинаковые значения или NULL-значения. Для создания индекса совсем не обязательно, чтобы значения столбца были уникальны. Приведем ряд рекомендаций, обеспечивающих нужное повышение производительности при использовании стандартного индекса, а также рассмотрим вопросы, связанные с балансом между производительностью и расходованием дискового пространства при создании индекса.
Использование индексов для поиска информации в таблицах может дать значительное повышение производительности по сравнению с просмотром таблиц, столбцы которых неиндексированы. Однако выбрать правильный индекс совсем непросто. Конечно, для индексирования с помощью индекса В-дерева предпочтителен столбец, все значения которого уникальны, но и столбец, не отвечающий этим требованиям,— неплохой кандидат, если только одинаковые значения содержатся примерно в 10% его строк и никак не более. Столбцы-«переключатели», или «флаги», например те в которых хранятся сведения о поле человека, для индексов В-дерева не годятся Не подходят и те столбцы, которые используются для хранения небольшого числа «достоверных значений», а также хранящие какие-то признаки, например «достоверность» или «недостоверность», «активность» или «неактивность», «да» или «нет» и т. д, и т. п. Наконец, индексы с обратными ключами применяются, как правило, там, где установлен и функционирует Oracle Parallel Server и нужно до максимума повысить уровень параллельности в базе данных.
Вы должны войти, чтобы оставить комментарий.
Типы данных UROWID и ROWID в PL/SQL
Учтите, что значения ROWID в таблицах могут изменяться. В ранних версиях Oracle (Oracle8 и ранее) значения ROWIDs оставались неизменными на протяжении жизненного цикла строки. Но в версии Oracle8i были добавлены новые возможности, нарушающие это старое правило. Если для обычной или индексной таблицы разрешено перемещение строк, обновление может привести к изменению ROWID или UROWID строки. Кроме того, если с таблицей будет выполнена операция, из-за которой строка перейдет из одного физического блока данных в другой блок, значение ROWID строки изменится.
Впрочем, даже с учетом этого предупреждения значения ROWID приносят практическую пользу. Включение значений ROWID в командах SELECT, UPDATE, MERGE и DELETE в некоторых случаях повышает скорость обработки, поскольку обращение к строке по ее идентификатору выполняется быстрее, чем по первичному ключу. На рис. 1 использование ROWID в команде UPDATE сравнивается с использованием значений столбцов (например, первичного ключа).
Рис. 1. Идентификатор ROWID ссылается непосредственно на строку таблицы
Получение идентификаторов строк
Чтобы получить ROWID для строки таблицы, добавьте ключевое слово в список выборки.
В терминологии Oracle ROWID называется «псевдостолбцом», потому что на самом деле столбца с именем ROWID в таблице не существует. Значение ROWID ближе к указателю — оно содержит физический адрес строки в таблице.
Конечно, использование ROWID ускоряет работу программ PL/SQL, потому что вы по сути опускаетесь на физический уровень управления базой данных. Однако хорошие приложения обычно не зависят от физической структуры данных. Они поручают управление физической структурой базе данных и административным программам, а сами ограничиваются логическим управлением данными. По этой причине использовать ROWID в приложениях обычно не рекомендуется.
Что такое rowid в oracle
DBMS_ROWID is not to be used with universal ROWIDs ( UROWIDs ).
This chapter contains the following topics:
147.1 DBMS_ROWID Security Model
147.2 DBMS_ROWID Types
There are four DBMS_ROWID types.
Extension and restriction types
Extension and Restriction Type
The types are as follows:
RESTRICTED —restricted ROWID
EXTENDED —extended ROWID
Extended ROWIDs are only used in Oracle database version 8.X i and higher.
Table 147-1 Verification Types
Result
Description
Table 147-2 Object Types
Result
Description
Object Number not defined (for restricted ROWIDs )
Table 147-3 Conversion Types
Result
Description
Convert to/from column of ROWID type
Convert to/from string format
147.3 DBMS_ROWID Exceptions
This table describes the Exceptions raised by DBMS_ROWID subprograms.
Table 147-4 Exceptions
Exception
Description
Invalid rowid format
Block is beyond end of file
147.4 DBMS_ROWID Operational Notes
You can call the DBMS_ROWID functions and procedures from PL/SQL code, and you can also use the functions in SQL statements.
ROWID_INFO is a procedure. It can only be used in PL/SQL code.
You can use functions from the DBMS_ROWID package just like built-in SQL functions; in other words, you can use them wherever you can use an expression. In this example, the ROWID_BLOCK_NUMBER function is used to return just the block number of a single row in the EMP table:
A problem with the current procedure or function
Calling a procedure or function without a pragma or due to calling one with a less restrictive pragma
Calling a package procedure or function that touches the initialization code in a package or that sets the default values
147.5 DBMS_ROWID Examples
147.6 Summary of DBMS_ROWID Subprograms
This table lists the DBMS_ROWID subprograms and briefly describes them.
Table 147-5 DBMS_ROWID Package Subprograms
Subprogram
Description
Returns the block number of a ROWID
Returns the type and components of a ROWID
Returns the object number of the extended ROWID
Returns the file number of a ROWID
Returns the row number
Returns the absolute file number associated with the ROWID for a row in a specific table
Converts a ROWID from restricted format to extended
Converts an extended ROWID to restricted format
Returns the ROWID type: 0 is restricted, 1 is extended
Checks if a ROWID can be correctly extended by the ROWID_TO_EXTENDED function
147.6.1 ROWID_BLOCK_NUMBER Function
Table 147-6 ROWID_BLOCK_NUMBER Function Parameters
Parameter
Description
ROWID to be interpreted
The type of the tablespace (bigfile/smallfile) to which the row belongs
The example SQL statement selects the block number from a ROWID and inserts it into another table:
147.6.2 ROWID_CREATE Function
This is useful for testing ROWID operations, because only the Oracle Server can create a valid ROWID that points to data in a database.
Table 147-7 ROWID_CREATE Function Parameters
Parameter
Description
Type (restricted or extended)
Data object number ( rowid_object_undefined for restricted)
Relative file number
Block number in this file
Returns row number in this block
Create a dummy extended ROWID :
Find out what the rowid_object function returns:
The variable obj_number now contains 9999.
147.6.3 ROWID_INFO Procedure
This is a procedure, and it cannot be used in a SQL statement.
Table 147-8 ROWID_INFO Procedure Parameters
Parameter
Description
Returns type (restricted/extended)
Returns data object number ( rowid_object_undefined for restricted)
Returns relative file number
Returns block number in this file
Returns row number in this block
This example reads back the values for the ROWID that you created in the ROWID_CREATE :
147.6.4 ROWID_OBJECT Function
Table 147-9 ROWID_OBJECT Function Parameters
Parameter
Description
ROWID to be interpreted
147.6.5 ROWID_RELATIVE_FNO Function
This function returns the relative file number of the ROWID specified as the IN parameter. (The file number is relative to the tablespace.)
Table 147-10 ROWID_RELATIVE_FNO Function Parameters
Parameter
Description
ROWID to be interpreted
Type of the tablespace (bigfile/smallfile) to which the row belongs
The example PL/SQL code fragment returns the relative file number:
147.6.6 ROWID_ROW_NUMBER Function
This function extracts the row number from the ROWID IN parameter.
Table 147-11 ROWID_ROW_NUMBER Function Parameters
Parameter
Description
ROWID to be interpreted.
Select a row number:
147.6.7 ROWID_TO_ABSOLUTE_FNO Function
The schema name and the name of the schema object (such as a table name) are provided as IN parameters for this function.
Table 147-12 ROWID_TO_ABSOLUTE_FNO Function Parameters
Parameter
Description
ROWID to be interpreted
Name of the schema which contains the table
For partitioned objects, the name must be a table name, not a partition or a sub/partition name.
147.6.8 ROWID_TO_EXTENDED Function
This function translates a restricted ROWID that addresses a row in a schema and table that you specify to the extended ROWID format.
Later, it may be removed from this package into a different place.
Table 147-13 ROWID_TO_EXTENDED Function Parameters
Parameter
Description
ROWID to be converted
Name of the schema which contains the table (optional)
Table name (optional).
The following constants are defined:
If the schema and object name are not provided (are passed as NULL ), then this function attempts to fetch the page specified by the restricted ROWID provided. It treats the file number stored in this ROWID as the absolute file number. This can cause problems if the file has been dropped, and its number has been reused prior to the migration. If the fetched page belongs to a valid table, then the data object number of this table is used in converting to an extended ROWID value. This is very inefficient, and Oracle recommends doing this only as a last resort, when the target table is not known. The user must still know the correct table name at the time of using the converted value.
If an extended ROWID value is supplied, the data object number in the input extended ROWID is verified against the data object number computed from the table name parameter. If the two numbers do not match, the INVALID_ROWID exception is raised. If they do match, the input ROWID is returned.
ROWID_TO_EXTENDED cannot be used with partition tables.
The ROWID_VERIFY Function has a method to determine if a given ROWID can be converted to the extended format.
90 DBMS_ROWID
DBMS_ROWID is not to be used with universal ROWIDs ( UROWIDs ).
This chapter contains the following topics:
Using DBMS_ROWID
Security Model
Types
Extension and Restriction Types
The types are as follows:
RESTRICTED —restricted ROWID
EXTENDED —extended ROWID
Extended ROWIDs are only used in Oracle database version 8.X i and higher.
Verification Types
Table 90-1 Verification Types
Result
Description
Object Types
Table 90-2 Object Types
Result
Description
Object Number not defined (for restricted ROWIDs )
Conversion Types
Table 90-3 Conversion Types
Result
Description
Convert to/from column of ROWID type
Convert to/from string format
Exceptions
Table 90-4 Exceptions
Exception
Description
Invalid rowid format
Block is beyond end of file
Operational Notes
You can call the DBMS_ROWID functions and procedures from PL/SQL code, and you can also use the functions in SQL statements.
ROWID_INFO is a procedure. It can only be used in PL/SQL code.
You can use functions from the DBMS_ROWID package just like built-in SQL functions; in other words, you can use them wherever you can use an expression. In this example, the ROWID_BLOCK_NUMBER function is used to return just the block number of a single row in the EMP table:
If Oracle returns the error «ORA:452, 0, ‘Subprogram ‘%s’ violates its associated pragma’ for pragma restrict_references, it could mean the violation is due to:
A problem with the current procedure or function
Calling a procedure or function without a pragma or due to calling one with a less restrictive pragma
Calling a package procedure or function that touches the initialization code in a package or that sets the default values
Examples
Summary of DBMS_ROWID Subprograms
Table 90-5 DBMS_ROWID Package Subprograms
Subprogram
Description
Returns the block number of a ROWID
Returns the type and components of a ROWID
Returns the object number of the extended ROWID
Returns the file number of a ROWID
Returns the row number
Returns the absolute file number associated with the ROWID for a row in a specific table
Converts a ROWID from restricted format to extended
Converts an extended ROWID to restricted format
Returns the ROWID type: 0 is restricted, 1 is extended
Checks if a ROWID can be correctly extended by the ROWID_TO_EXTENDED function
ROWID_BLOCK_NUMBER Function
Table 90-6 ROWID_BLOCK_NUMBER Function Parameters
Parameter
Description
ROWID to be interpreted.
The type of the tablespace (bigfile/smallfile) to which the row belongs.
The example SQL statement selects the block number from a ROWID and inserts it into another table:
ROWID_CREATE Function
This is useful for testing ROWID operations, because only the Oracle Server can create a valid ROWID that points to data in a database.
Table 90-7 ROWID_CREATE Function Parameters
Parameter
Description
Type (restricted or extended).
Data object number ( rowid_object_undefined for restricted).
Relative file number.
Block number in this file.
Returns row number in this block.
Create a dummy extended ROWID :
Find out what the rowid_object function returns:
The variable obj_number now contains 9999.
ROWID_INFO Procedure
Table 90-8 ROWID_INFO Procedure Parameters
Parameter
Description
The type of the tablespace (bigfile/smallfile) to which the row belongs.
Returns type (restricted/extended).
Returns data object number ( rowid_object_undefined for restricted).
Returns relative file number.
Returns block number in this file.
Returns row number in this block.
This example reads back the values for the ROWID that you created in the ROWID_CREATE :
ROWID_OBJECT Function
Table 90-9 ROWID_OBJECT Function Parameters
Parameter
Description
ROWID to be interpreted.
ROWID_RELATIVE_FNO Function
This function returns the relative file number of the ROWID specified as the IN parameter. (The file number is relative to the tablespace.)
Table 90-10 ROWID_RELATIVE_FNO Function Parameters
Parameter
Description
ROWID to be interpreted.
The type of the tablespace (bigfile/smallfile) to which the row belongs.
The example PL/SQL code fragment returns the relative file number:
ROWID_ROW_NUMBER Function
This function extracts the row number from the ROWID IN parameter.
Table 90-11 ROWID_ROW_NUMBER Function Parameters
Parameter
Description
ROWID to be interpreted.
Select a row number:
ROWID_TO_ABSOLUTE_FNO Function
Table 90-12 ROWID_TO_ABSOLUTE_FNO Function Parameters
Parameter
Description
ROWID to be interpreted.
Name of the schema which contains the table.
For partitioned objects, the name must be a table name, not a partition or a sub/partition name.
ROWID_TO_EXTENDED Function
This function translates a restricted ROWID that addresses a row in a schema and table that you specify to the extended ROWID format. Later, it may be removed from this package into a different place.
Table 90-13 ROWID_TO_EXTENDED Function Parameters
Parameter
Description
ROWID to be converted.
Name of the schema which contains the table (optional).
Table name (optional).
The following constants are defined:
If the schema and object name are not provided (are passed as NULL ), then this function attempts to fetch the page specified by the restricted ROWID provided. It treats the file number stored in this ROWID as the absolute file number. This can cause problems if the file has been dropped, and its number has been reused prior to the migration. If the fetched page belongs to a valid table, then the data object number of this table is used in converting to an extended ROWID value. This is very inefficient, and Oracle recommends doing this only as a last resort, when the target table is not known. The user must still know the correct table name at the time of using the converted value.
If an extended ROWID value is supplied, the data object number in the input extended ROWID is verified against the data object number computed from the table name parameter. If the two numbers do not match, the INVALID_ROWID exception is raised. If they do match, the input ROWID is returned.
The ROWID_VERIFY Function has a method to determine if a given ROWID can be converted to the extended format.
ROWID_TO_RESTRICTED Function
This function converts an extended ROWID into restricted ROWID format.
Table 90-14 ROWID_TO_RESTRICTED Function Parameters
Parameter
Description
ROWID to be converted.
The following constants are defined:
ROWID_TYPE Function
Table 90-15 ROWID_TYPE Function Parameters
Parameter
Description
ROWID to be interpreted.
ROWID_VERIFY Function
You can use this function in a WHERE clause of a SQL statement, as shown in the example.
Table 90-16 ROWID_VERIFY Function Parameters
Parameter
Description
ROWID to be verified.
Name of the schema which contains the table.
The following constants are defined:
Considering the schema in the example for the ROWID_TO_EXTENDED function, you can use the following statement to find bad ROWID s prior to conversion. This enables you to fix them beforehand.