Showing posts with label HCC. Show all posts
Showing posts with label HCC. Show all posts

Friday, September 6, 2019

In defense of HCC: ORA-39726: unsupported add/drop column operation on compressed tables

A friend asked to check the

ISSUE:
ORA-39726 is hit when adding column with default value to basic compressed table.

CAUSE:
compressed table will not allow some operation, which are allowed in uncompressed table.


"Is there any error during add column with default value to table compressed with HCC ?
Does Oracle unpack HCC data during add column with default value to the table compressed with HCC ?"  he asked.

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

And the answer is here.

RDBMS version is 12.1.0.2.171017 (i choosed old enough version i can find. newer versions belived work the same).

$ opatch lspatches
26635845;Database PSU 12.1.0.2.171017, Oracle JavaVM Component (OCT2017)
25729214;OCW Interim patch for 25729214
26717470;Database Bundle Patch : 12.1.0.2.171017 (26717470)



$ sqlplus / as sysdba
SQL> create tablespace yu extent management local segment space management auto;
SQL> create user yu identified by yu default tablespace yu;
SQL> grant dba to yu ;

SQL> conn yu/yu

SQL> create table NOCOMP as select owner,object_type,object_name,object_id,created from dba_objects order by owner,object_type,object_name;
insert into nocomp select * from nocomp;
insert into nocomp select * from nocomp;
insert into nocomp select * from nocomp;
insert into nocomp select * from nocomp;
commit;

Table created.

SQL>
151156 rows created.

SQL>
302312 rows created.

SQL>
604624 rows created.

SQL>
1209248 rows created.

SQL>
Commit complete.

SQL> select table_name from user_tables;

TABLE_NAME
--------------------------------------------
NOCOMP

SQL> select segment_name, bytes, bytes/1048576 MB, blocks from user_segments order by 1;

SEGMENT_NAME        BYTES   MB    BLOCKS
-------------- ---------- ------- ----------
NOCOMP          159383552   152   9728


SQL> create table BASICOMP compress as select * from NOCOMP;

create table OLTPCOMP  compress for OLTP as select * from NOCOMP;

create table QL   compress for query LOW as select * from NOCOMP;
create table QLRL compress for query LOW row level locking as select * from NOCOMP;

create table QH   compress for query HIGH as select * from NOCOMP;
create table QHRL compress for query HIGH row level locking as select * from NOCOMP;

create table AL   compress for archive LOW as select * from NOCOMP;
create table ALRL compress for archive LOW row level locking as select * from NOCOMP;

create table AH   compress for archive HIGH as select * from NOCOMP;
create table AHRL compress for archive HIGH row level locking as select * from NOCOMP;


Table created.

SQL>
Table created.

SQL> SQL>
Table created.

SQL>
Table created.

SQL> SQL>
Table created.

SQL>
Table created.

SQL> SQL>
Table created.

SQL>
Table created.

SQL> SQL>
Table created.

SQL>
Table created.

SQL> exec dbms_stats.gather_schema_stats('YU');
PL/SQL procedure successfully completed.

SQL> col segment_name for a8
SQL> select segment_name, bytes, bytes/1048576 MB, blocks from user_segments order by 2 desc;

SEGMENT_      BYTES        MB     BLOCKS
-------- ---------- ---------- ---------

NOCOMP    159383552       152       9728
OLTPCOMP  100663296        96       6144
BASICOMP   92274688        88       5632
QLRL       47185920        45       2880
QL         44040192        42       2688
QHRL       26214400        25       1600
ALRL       25165824        24       1536
QH         24117248        23       1472
AL         23068672        22       1408
AHRL       18874368        18       1152
AH         16777216        16       1024

SQL> col table_name for a8
SQL> select table_name,num_rows,blocks from user_tables order by blocks desc;

TABLE_NA   NUM_ROWS    BLOCKS
-------- ---------- ---------
NOCOMP      2418496      9652
OLTPCOMP    2418496      5799
BASICOMP    2418496      5211
QLRL        2418496      2848
QL          2418496      2670
QHRL        2418496      1577
ALRL        2418496      1492
QH          2418496      1456
AL          2418496      1400
AHRL        2418496      1148
AH          2418496      1010

SQL> 

alter table NOCOMP   add new_column number(3) default 0;
alter table BASICOMP add new_column number(3) default 0;
alter table OLTPCOMP add new_column number(3) default 0;
alter table QLRL     add new_column number(3) default 0;
alter table QL       add new_column number(3) default 0;
alter table QHRL     add new_column number(3) default 0;
alter table ALRL     add new_column number(3) default 0;
alter table QH       add new_column number(3) default 0;
alter table AL       add new_column number(3) default 0;
alter table AHRL     add new_column number(3) default 0;
alter table AH       add new_column number(3) default 0;
Table altered.

alter table BASICOMP add new_column number(3) default 0
                        *
ERROR at line 1:
ORA-39726: unsupported add/drop column operation on compressed tables

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL>
Table altered.

SQL> exec dbms_stats.gather_schema_stats('YU');
PL/SQL procedure successfully completed.

SQL> col segment_name for a8
SQL> select segment_name, bytes, bytes/1048576 MB, blocks from user_segments order by 2 desc;

SEGMENT_      BYTES     MB   BLOCKS  BLOCKS before add column
-------- ---------- ------- ------- --------------------------

NOCOMP    159383552    152     9728    9728
OLTPCOMP  100663296     96     6144    6144
BASICOMP   92274688     88     5632    5632
QLRL       47185920     45     2880    2880
QL         44040192     42     2688    2688
QHRL       26214400     25     1600    1600
ALRL       25165824     24     1536    1536
QH         24117248     23     1472    1472
AL         23068672     22     1408    1408
AHRL       18874368     18     1152    1152
AH         16777216     16     1024    1024

SQL> col table_name for a8
SQL> select table_name,num_rows,blocks from user_tables order by blocks desc;

TABLE_NA   NUM_ROWS    BLOCKS   BLOCKS before add column

-------- ---------- ----------   ------------------------
NOCOMP      2418496      9652     9652
OLTPCOMP    2418496      5799     5799
BASICOMP    2418496      5211     5211
QLRL        2418496      2848     2848
QL          2418496      2670     2670
QHRL        2418496      1577     1577
ALRL        2418496      1492     1492
QH          2418496      1456     1456
AL          2418496      1400     1400
AHRL        2418496      1148     1148
AH          2418496      1010     1010


No one block is added after ADD COLUMN modification!

As you can see the only issue for BASIC COMPRESSION:

alter table BASICOMP add new_column number(3) default 0
                         *
ERROR at line 1:
ORA-39726: unsupported add/drop column operation on compressed tables

In other cases "alter table add column" work well: no decompression at all.
As the DOC 12.1.0.2 say:
"... the default value is stored as metadata, the column itself is not populated with data"




Friday, August 1, 2014

Standby for Exadata on non-Exadata storage




> is it possible to have standby for Exadata on non-Exadata storage ( EMC, HP ...) 
  
Физический стендбай для Эзадаты МОЖНО держать на обычном х86-64 сервере с обычным хранилищем. НСС-сегменты нормально обновляются процессом Redo Apply, т.е. изменения в НСС-сегментах будут применяться к стендбаю, т.е. стендбай будет актуальным. Операция Redo Apply выполняется над НСС-данными без декомпрессии.
Однако, при выполнении SELECT к НСС-сегментам будут происходить ошибки.
Но и в этом случае есть выход: операция Alter Table Move разожмет НСС-сегменты и превратит их в блоки сжатые OLTP-компрессией.
И тогда все ваши данные станут вам доступны.
Вот таков официально заявленный функционал.
---------------------------------------------------
Yes. 
It is possible to run physical standby for Exadata on non-Exadata equipment.
Take
- any server x86-64 (Supermicro for example)
- any 64-bit Linux   (5.9 or 6.4 for example)
- Oracle RDBMS of the same version as on the Exadata

You can ommit ASM and RAC on non-Exadata equipment and get single instance on file system.
You can copy database with RMAN as DUPLICATE ... or restore from backup and setup redo shipping and redo apply.

HCC-segments are updatable with Redo Apply, so your standby will be actual and be able to run behind production.  Redo Apply is performed on the HCC-data without decompression.

You'll get the error after you run SELECT to the HCC-segments.
But in this case you have a backdoor: Alter Table Move will decompress your HCC-segments into OLTP-compresses blocks and you'll be able to run SELECT against former HCC-segments.


Friday, February 14, 2014

Tables will inherit HCC compression from Tablespace

We are on the Exadata.
The idea: to create the tablespace with HCC and move tables there.
Will tables be HCC-compressed ? Will tables inherit the COMPRESS FOR from the tablespace ?

Today i did the test and answer is YES !

Test env: we have the table BILLS in the non-HCC tablespace.
I created the new tablespace:

SQL> create bigfile tablespace HCC blocksize 8k datafile '+DATAC1'
size 1344m autoextend on next 1344m maxsize unlimited
default COMPRESS FOR QUERY HIGH
extent management local uniform size 4m
segment space management auto;

Tablespace created.


SQL> create table BILLS_HCC tablespace HCC as select * from BILLS;

Table created.


SQL> select segment_name, bytes from dba_segments where segment_name like 'BILLS%';

SEGMENT_NAME             BYTES
------------ -----------------
BILLS              27313307648
BILLS_HCC           6954156032


SQL> select 27313307648/6954156032 from dual;

27313307648/6954156032
----------------------
  3.927623642943305187


SQL> select table_name, compression,compress_for from dba_tables where table_name like 'BILLS%';

TABLE_NAME       COMPRESS COMPRESS_FOR
---------------- -------- ------------
BILLS_HCC        ENABLED  QUERY HIGH
BILLS            DISABLED

SQL> set timing on
SQL> select count(*) from BILLS;

            COUNT(*)
--------------------
           146432303

Elapsed: 00:00:02.83
SQL> select count(*) from BILLS_HCC;

            COUNT(*)
--------------------
           146432303

Elapsed: 00:00:02.65

Wednesday, November 6, 2013

Oracle vs Hana


 Посетив на днях семинар по HANA, хочу поделиться своими выводами.

Сила ХАНЫ заключается в следующих вещах:
- хранение таблиц в формате столбцевой компрессии (коэффициент сжатия SAP считает около 6)
- хранение данных в оперативной памяти (предполагается, что в сочетании со сжатием все данные должны поместиться в оперативную память. Пропорция для расчета: 64Г оперативной памяти на каждые 300Г исходных пользовательских данных. при чтении одной строки из таблицы вся таблица/партиция читается в оперативную память)
- кроме того, SAP внедрили в ХАНУ обычный row-store движок (надо полагать, это кусочек от ранее купленного Sybase), который позволяет работать с таблицами в обычном строчном row-формате. Этот формат хранения предназначается для OLTP-приложений.

В результате, получилась забавная гибридная СУБД, способная работать как с DWH-приложениями так и OLTP. Справедливости ради надо сказать, что все современные OLTP-движки – DB2, MSSQL, Sybase, Postgress – значительно уступают OLTP-движку от Оракла, т.е. для тяжелого OLTP они просто не подходят по причине роста блокировок.


Поэтому Оракл немедленно взялся за Database-In-Memory Option, которая по сути есть НСС не привязанное к системе хранения, иными словами, Оракл повторно, с 5-летним опозданием, анонсирует свою НСС-опцию:




Oracle Database In-Memory leverages a new in-memory column store format

Oracle Database In-Memory option accelerates the performance of analytic queries by storing data in a highly optimized columnar in-memory format.

A unique "dual-format" approach ensures outstanding performance and complete data consistency for all workloads.

Oracle Database In-Memory automatically maintains data in both the existing Oracle row format for OLTP operations, and a new purely in-memory column format optimized for analytical processing. Both formats are simultaneously active and transactionally consistent.



Для тех кто не в курсе: Оракл имеет HCC с 2008 года, когда вышла первая Экзадата. Но Оракл разрешил HCC только для своих собственных систем хранения: Exadata Storage Cell, Pillar Axiom, ZFS Storage Appliance. Вот если бы Оракл изначально объявил этот функционал своей опцией, доступной на всех платформах, то мы бы сейчас видели бурный всплеск продаж СУБД.

Столбцевое хранение данных на сегодняшний тень также реализовано в MS SQL, IBM DB2 & Netezza. Таким образом, можно сделать вывод, что современные СУБД все больше становятся гибридными, т.е.  способными хранить/обрабатывать оба типа данных.

Monday, July 15, 2013

HCC Advisor

You can test the Exadata HCC compression on your production non-Exadata server (for example, on your HP Superdome or IBM 795).
It is free. It is safe. It is quick. It is easy.

Pre-Requisites: you have to choose the appropriate OWNER.TABLE and have enough space in the TABLESPACE. And decide,please, which one of type compression you will test
- Query Low
- Query High
- Archive Low
- Archive High
 
Take the dbms_compression.get_compression_ratio function for it, it has the name of "HCC Advisor"

Look at the example :

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

set serveroutput on
declare
 v_blkcnt_cmp     pls_integer;
 v_blkcnt_uncmp   pls_integer;
 v_row_cmp        pls_integer;
 v_row_uncmp      pls_integer;
 v_cmp_ratio      number;
 v_comptype_str   varchar2(60);
begin
 dbms_compression.get_compression_ratio(
 scratchtbsname   => upper('&Tablespace'),  -- Tablespace Name   
 ownname          => upper('&UserName'),    -- USER NAME
 tabname          => upper('&TableName'),   -- TABLE NAME
 partname         => NULL,          
 comptype         => dbms_compression.comp_for_query_high, --compression type 
 blkcnt_cmp       => v_blkcnt_cmp,   
 blkcnt_uncmp     => v_blkcnt_uncmp, 
 row_cmp          => v_row_cmp,   
 row_uncmp        => v_row_uncmp, 
 cmp_ratio        => v_cmp_ratio, 
 comptype_str     => v_comptype_str);
 dbms_output.put_line('Estimated Compression Ratio: '||to_char(v_cmp_ratio));
 dbms_output.put_line('Blocks used by compressed sample: '||to_char(v_blkcnt_cmp));
 dbms_output.put_line('Blocks used by uncompressed sample: '||to_char(v_blkcnt_uncmp));
end;
/


Estimated Compression Ratio: 13.6
Blocks used by compressed sample: 1041
Blocks used by uncompressed sample: 14251

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

Common Errors:
ORA-20000: Compression Advisor scratch tablespace cannot be UNIFORM tablespace
ORA-20000: Compression Advisor must have at least 1000000 rows in this



 

Wednesday, July 10, 2013

SAP + HCC = engagement

As we know, SAP does not recommend the use of the HCC.
Therefore the using of Exadata for SAP does not give the full effect: large database are remained large...
Leveraging the HCC for SAP DB will change the matters and the effect will be greater.



http://www.oracle.com/us/solutions/sap/sap-database/index.html

"
Currently we are testing the following Oracle Database 12c options and features for SAP:
- Hybrid Columnar Compression (HCC)
"


Monday, February 4, 2013

HCC on the Pillar Axiom

Oracle позволяет использовать HCC-компрессию не только на Экзадате, но и на ZFS storage appliance и на Pillar Axiom.  Если в качестве сервера взять T4 + Solaris 11, то получится отличная платформа для консолидации данных: много потоков и НСС впридачу!

Покажем работающи пример :

0. Берем сервер Т4, инсталлируем на нем Солярис 11. На Axiom создаем LUN и презентуем его серверу - все как всегда.

1. Компрессия возможна только на сырых томах (не на файловой системе), поэтому используем ASM, поэтому поэтому первым делом инсталлируем GI.

2. Для HCC требуется версия GI не ниже 11.2.3.0.3. В более ранних версиях оно не работает. Поэтому я взял последний PSU от January 2013 - ставим его на GI.

3. В ASM cоздаем дисковую группу. Для данной группы устанавливаем два обязательных параметра:
alter diskgroup data set attribute 'compatible.asm'='11.2.0.3';
alter diskgroup data set attribute 'storage.type'='AXIOM';

Если некоторая дисковая группа уже создана и в ней уже лежит БД, то ничего страшного - надо остановить БД и установить параметры. Причем, первый параметр - 'compatible.asm' - можно менять без остановки БД, он динамический.

 4. Инсталлируем бинарники СУБД: опять берем последнюю версию - 11.2.0.3 - и последний PSU - January 2013. Инсталлируем Оракл и создаем БД на нашей дисковой группе.

Готово!




Статисика показывает, что около 75% данных в базе относятся к закрытым периодам - прошлый год, квартал.
Еще 20% - это активные данные, которые иногда меняются.
Еще 5% - это горячие данные, активно изменяющиеся.

Первая категория данных - это хорошие кандидаты на НСС. Если их пожать, например, в 10 раз, то объем базы значительно сократится. Затраты ЦПУ возрастают в 3 раза, но ввод-вывод сократится в 10 раз. В общем, прирост производительности налицо.
Вторую категорию можно объявить как OLTP Compression  - затрат ЦПУ практически никаких, а объемы уменьшаются в два раза.
Третью категорию оставляем как есть.

 

Monday, July 16, 2012

HCC and CPU consumption



We tested the CPU consumption for HCC and traditional segments.
We run select sum(Col1) from table  under the 10046 trace for traditional table and its compresses copies. 10046 trace shows the time in microseconds. All segments were in the SGA in order to exclude physical IO. Original table size was 16g, the compressed size is

------------------- ------------------ -------
Table type           Compression ratio   CPU
------------------- ------------------ -------
Original table            1               1
Compress for OLTP         1.8             0.8
QL                        4.9             3.3
QH                       20               3.5
AL                       20               3.5
AH                       59              11  
----------------------------------------------
            
As you can see QL, QH, AL takes 3.3-3.5 more CPU cycles (CPU time).
But we see the significant compression ratio for HCC segments.
Therefore, if any select in traditional DB spend 90% time in IO wait and 10% time in CPU
then with 10-times compression it will spend 30% on the CPU and 90/10=9% in IO = 39% of original time.

The packing time depends on the compression ratio (the more compression ratio the more time to create HCC segment).

The unpacking time not depends on the compression ratio.

HCC algorithms are:

Query Low  - LZO
Query High - ZLIB
Archive Low - ZLIB
Archive High - bzip2

Friday, October 21, 2011

HCC

Thanks to Tanel:

QUERY LOW - uses the LZO compression algorithm. Fastest.
QUERY HIGH - uses the ZLIB (gzip) compression algorithm.
ARCHIVE LOW - uses the ZLIB (gzip) compression algorithm, but at a higher compression level than QUERY HIGH.
ARCHIVE HIGH - uses Bzip2 compression. This is the highest level of compression available but is  most CPU-intensive.

Monday, October 17, 2011

11.2.0.3 New Features

Следуем простому старому правилу: 1 час каждый рабочий день посвящать чтению документации. Сегодня:
http://download.oracle.com/docs/cd/E11882_01/server.112/e22487/chapter1_11203.htm

Итак, что мы видим в новых возможностях 11.2.0.3?

- Support Hybrid Columnar Compression on Pillar Axiom and Sun ZFSSA - гибридно-столбцевая компрессия широко шагает по планете и теперь поддерживается на новых железках. Но для этого нужно стаивить 11.2.0.3.


- В своих тренингах по Экзадате я уже рассказывал, что процессоры Intel Xeon 5600 и выше (которые используются в Экзадате) - это революция, по сравнению с 5500 и предыдущими. В частности, они оснащены аппаратным модулем шифрования. А аппаратное шифрование на порядок быстрее программного. И есть ноты, которые подтверждают, что Оракл 11.2 использует это самое аппаратное шифрование. В новых ядрах Т4 тоже была расширена аппаратная криптография и СУБД Oracle ее использует:

" 3.1.3 TDE Hardware Acceleration for Solaris
Transparent Data Encryption (TDE) can automatically detect whether the database host machine includes specialized cryptographic silicon that accelerates the encryption or decryption processing. When detected, TDE uses the specialized silicon for cryptographic processing accelerating the overall cryptographic performance significantly.
In prior releases, cryptographic hardware acceleration for TDE was only available on Intel Xeon, and only for Linux. With release 11.2.0.3 and later releases, it works with the current versions of Solaris 11 running on both SPARC T-Series and Intel Xeon.
"


Thursday, May 19, 2011

Эксперименты с компрессией


Попробовал сделать две таблицы из одного дампа:HCCAH archive high и 
HCCQH - query high.

Сам дамп 20g ( создавался с опцией expdp COMPRESS=Y)
Табличка без сжатия = 500g.

И прогнал по обеим select count(*) from &1;


Таблица            HCC            Size         count(*)
----------------------------------------------------------------------------------
HCCQH        query high         139g         13 s
HCCAH        archive high       129g          25 s
-------------------------------------------------------------------------------------

Выигрыш в сжатии небольшой, а скорость запросов падает заметно.
Вывод: буду рекомендовать HCC query high. 


select NUM_ROWS,BLOCKS,AVG_ROW_LEN from dba_tables where table_name='HCCQH';

NUM_ROWS     BLOCKS   AVG_ROW_LEN
---------- ---------- -----------
1866884241   18238956         227


Чтобы посчитать объем данных который потребуется на диске среднюю длину строки умножаем на кол-во строк

select round( NUM_ROWS * AVG_ROW_LEN /1024/1024/1024) as GB from dba_tables where table_name='HCCQH';

        GB
 ---------
       395
 
А теперь смотрим объем таблицы исходя из кол-ва блоков:

select round( BLOCKS /1024/1024/1024) as GB from dba_tables where table_name='HCCQH';

       GB
---------
      139

Получается, 395g строк помещаются в 139g блоков.




 

# ocrconfig -add +DATA PROT-30: The Oracle Cluster Registry location to be added is not usable. PROC-50: The Oracle Cluster Registry locatio...