27 июня 2011 г.

windows: hotkeys

Ctrl+Shift+Esc - Диспетчер задач

Win+Up - Развернуть окно
Win+Down - Восстановить / Минимизировать окно
Win+Left - Прикрепить окно к левому краю экрана
Win+Right - Прикрепить окно к правому краю экрана
Win+Shift+Left - Переключиться на левый монитор
Win+Shift+Right - Переключиться на правый монитор
Win+Home - Минимизировать / Восстановить все окна
Win+Т - Выбрать первый элемент в панели задач (Повторное нажатие переключает на следующий элемент, Win+Shift+T - прокручивает в обратном порядке)
Win+Space - Показать рабочий стол
Win+G - Отобразить гаджеты поверх всех окон
Win+P - Отобразить дополнительные опции дисплея (расширить рабочий стол на 2 монитор и т.п.)
Win+X - Запустить Mobility Center
Win+ цифра- Запустить приложение с панели задач (Win+1 запускает первое приложения слева, Win+2, второе, и т.к.)
Win + "+" - Увеличить масштаб
Win + "-" - Уменьшить мастшаб

Windows Explorer

Alt+P - Показать / Скрыть панель предпросмотра

Панель задач

Shift + щелчок на иконке - Открыть новое окно приложения
Ctrl + Shift + щелчок по иконке - Открыть новое окно приложения с привилегиями администратора
Shift + щелчок правой кнопкой на иконке - Показать меню приложения
Shift + щелчок правой кнопкой на группе иконок - Показать меню, восстановить все / cвернуть все / Закрыть все
Ctrl + щелчок по группе икнонок - Развернуть все окна группы

10 июня 2011 г.

oracle: Слияние свободных экстентов в табличном пространстве

Это относится к табличным пространствам управляемых по словарю.

В процессе работы БД бывает такое, что несколько свободных экстентов идут друг за другом в таком случае их можно слить в один с помощью ALTER TABLESPACE tbs_name COALESCE

-- оценить фрагментацию

-- Если FSFI около 100 - фрагментации  нет
-- Если FSFI ближе к 0 - фрагментация есть
SELECT TABLESPACE_NAME,
     SQRT(MAX(BLOCKS)/SUM(BLOCKS))+
     (100/SQRT(SQRT(COUNT(BLOCKS)))) FSFI
    FROM DBA_FREE_SPACE
    GROUP BY TABLESPACE_NAME
    ORDER BY 1;

-- Посмотреть фрагментацию табличного пространства USERS (вариант 1)
SELECT   'free space' owner, '   ' OBJECT, file_id, block_id, blocks
    FROM dba_free_space
   WHERE tablespace_name = 'USERS'
UNION
SELECT   SUBSTR (owner, 1, 20), SUBSTR (segment_name, 1, 32), file_id,
         block_id, blocks
    FROM dba_extents
   WHERE tablespace_name = 'USERS'
ORDER BY 3, 4; 

-- Посмотреть фрагментацию табличного пространства USERS (вариант 2)
SELECT a.tablespace_name, a.file_id, a.block_id, a.blocks, b.block_id
  FROM dba_free_space a, dba_free_space b
 WHERE a.tablespace_name = 'USERS'
   AND b.tablespace_name = 'USERS'
   AND a.tablespace_name = b.tablespace_name
   AND a.file_id = b.file_id
   AND a.block_id + a.blocks = b.block_id;


-- выполнить слияние свободных экстентов
alter tablespace users coalesce;

9 июня 2011 г.

oracle: Index Scans

http://aguppi.blogspot.com/2011/06/oracle-access-path.html
Что такое индекс oracle: Index

Типы Index Scans:

  • Index Unique Scans
  • Index Range Scans
  • Index Range Scans Descending
  • Index Skip Scans
  • Full Scans
  • Fast Full Index Scans
  • Index Joins
  • Bitmap Joins


Index Unique Scans

Возвращает один rowid.
Происходит, если выражение использует индекс, который содержит ограничение UNIQUE или PRIMARY KEY, которые гарантирую что будет возвращена только одна строка.

Hints
/*+ INDEX( tab_name idx1_name idx2_name ...) */

Этот хинт указывает оптимизатору использывать индекс, но не определённый путь индексного доступа.
Обычно не нужно указывать хинт для Index Unique Scans. Но если используем db link или таблица мала и оптимизатор выбирает Full Table Scan, то можно указать хинт.

oracle: Rowid Scans

http://aguppi.blogspot.com/2011/06/oracle-access-path.html


  • Rowid определяет datafile и block, который содержит выбранную строку.
  • Это быстрейший способ получить строку, поскольку rowid прямо указывает на расположение строки.
  • Oracle получает rowid из выбранных с помощью конструкции WHERE либо с помощью index scan строк. Далее находит каждую выбранную строку таблицы с помощью rowid.

Когда оптимизатор выбирает Rowid Scans

Обычно Rowid Scans это второй шаг после получения rowid из индекса.
Но если индекс содержит все столбцы возвращаемые выражением, то Rowid Scans не выполняется, т.к. все нужные данные уже находятся после index scan.

oracle: HWM

High Water Mark (HWM)


  • Отметка для таблицы максимального уровня блоков, которые были когда либо заполнены.
  • Ниже HWM находятся блоки. которые имеют данные или когда то имели их.
  • Выше HWM находятся никогда не использовавшиеся блоки.
  • HWM хранится в DBA_TABLES.BLOCKS.
  • HWM используется как конечный маркер(блок), который нужно прочитать при Full Table Scans.
  • HWM сбрасывается когда таблица dropped или truncate.

For example, consider a table that had a large number of rows in the past. Most of the rows have been deleted, and now most of the blocks under the high water mark are empty. A full table scan on this table exhibits poor performance because all the blocks under the high water mark are scanned.

oracle: Full Table Scans

http://aguppi.blogspot.com/2011/06/oracle-access-path.html
  • Читает все строки таблицы ниже HWM .
  • Оптимален для получения большого количества данных из таблицы.
  • Блоки читаются последовательно, поэтому можно настроить I/O, чтобы за раз считывалось несколько блоков. Настраиваем параметр инициализации DB_FILE_MULTIBLOCK_READ_COUNT.
  • Каждый блок читается только один раз.
  • Если есть условия, то запрос отбрасывает строки не попадающие под условия.
Когда оптимизатор использует Full Table Scans

  • Отсутствие индекса, когда нет подходящего для запроса индекса.
  • Большое кол-во данных, когда оптимизатор предполагает, что запрос вернёт большинство строк таблицы.
  • Маленькая таблица, если дешевле прочитать всю таблицу, чем использовать индекс.
  • High Degree of Parallelism. A high degree of parallelism for a table skews the optimizer toward full table scans over range scans. Examine the DEGREE column in ALL_TABLES for the table to determine the degree of parallelism.
Hints
Чтобы принудительно использовать Full Table Scans используются хинты.
/*+ FULL(tab_name) */

SELECT /*+ FULL(e) */ employee_id, last_name
  FROM employees e
  WHERE last_name LIKE :b1;


2 июня 2011 г.

oracle: access path (путь доступа)

The access path determines the number of units of work required to get data from a base table. The access path can be a table scan, a fast full index scan, or an index scan.

Full Table Scans
Rowid Scans
Index Scans
Cluster Scans
Hash Scans
Sample Table Scans 

oracle: Селективность

Selectivity


The first measure, selectivity, represents a fraction of rows from a row set. The row set can be a base table, a view, or the result of a join or a GROUP BY operator. The selectivity is tied to a query predicate, such as last_name = 'Smith', or a combination of predicates, such as last_name = 'Smith' AND job_type = 'Clerk'. A predicate acts as a filter that filters a certain number of rows from a row set. Therefore, the selectivity of a predicate indicates how many rows from a row set will pass the predicate test. Selectivity lies in a value range from 0.0 to 1.0. A selectivity of 0.0 means that no rows will be selected from a row set, and a selectivity of 1.0 means that all rows will be selected.


The estimator uses an internal default value for selectivity, if no statistics are available. Different internal defaults are used, depending on the predicate type. For example, the internal default for an equality predicate (last_name = 'Smith') is lower than the internal default for a range predicate (last_name > 'Smith'). The estimator makes this assumption because an equality predicate is expected to return a smaller fraction of rows than a range predicate.


When statistics are available, the estimator uses them to estimate selectivity. For example, for an equality predicate (last_name = 'Smith'), selectivity is set to the reciprocal of the number n of distinct values of last_name, because the query selects rows that all contain one out of n distinct values. If a histogram is available on the last_name column, then the estimator uses it instead of the number of distinct values. The histogram captures the distribution of different values in a column, so it yields better selectivity estimates. Having histograms on columns that contain skewed data (in other words, values with large variations in number of duplicates) greatly helps the CBO generate good selectivity estimates.

1 июня 2011 г.

oracle: OPTIMIZER_MODE (режим оптимизации)

OPTIMIZER_MODE Initialization Parameter

The OPTIMIZER_MODE initialization parameter establishes the default behavior for choosing an optimization approach for the instance. The possible values and description are listed in Table 1-2.
Table 1-2  OPTIMIZER_MODE Parameter Values
Value Description
CHOOSE
The optimizer chooses between a cost-based approach and a rule-based approach, depending on whether statistics are available. This is the default value.
  • If the data dictionary contains statistics for at least one of the accessed tables, then the optimizer uses a cost-based approach and optimizes with a goal of best throughput.
  • If the data dictionary contains only some statistics, then the cost-based approach is still used, but the optimizer must guess the statistics for the subjects without any statistics. This can result in suboptimal execution plans.
  • If the data dictionary contains no statistics for any of the accessed tables, then the optimizer uses a rule-based approach.
ALL_ROWS
The optimizer uses a cost-based approach for all SQL statements in the session regardless of the presence of statistics and optimizes with a goal of best throughput (minimum resource use to complete the entire statement).
FIRST_ROWS_n
The optimizer uses a cost-based approach, regardless of the presence of statistics, and optimizes with a goal of best response time to return the first n number of rows; n can equal 1, 10, 100, or 1000.
FIRST_ROWS
The optimizer uses a mix of cost and heuristics to find a best plan for fast delivery of the first few rows.
Note: Using heuristics sometimes leads the CBO to generate a plan with a cost that is significantly larger than the cost of a plan without applying the heuristic. FIRST_ROWS is available for backward compatibility and plan stability.
RULE
The optimizer chooses a rule-based approach for all SQL statements regardless of the presence of statistics.