Visualizzazione post con etichetta Primary Key. Mostra tutti i post
Visualizzazione post con etichetta Primary Key. Mostra tutti i post

martedì 23 giugno 2015

Oracle Tips: creating a Primary Key over a big big table

I am currently working on an Exadata machine and trying to add a Primary Key (henceforth, PK) to a table that currently stores 629 milions of rows.
First attempt, I have simply executed the following statement:


alter table TAB add primary key (col_1, col_2, ... , col_n );


Big fail! The query run for more than 24 hours. It did not complete and I had to kill it manually.
Second attempt. Use the DISABLE NOVALIDATE option.

alter table TAB add constraint "PK_<name>" primary key  (col_1, col_2, ... , col_n ) DISABLE NOVALIDATE;

The creation itself is fast. The issue comes when you enable the key. It took forever again and I had to abort the process.
I finally decided to  adopt the CREATE INDEX strategy. Basically, you first create an index with the columns you want to be part of the primary key.

create index MYIDX on TAB (col_1, col_2, ... , col_n ) PARALLEL 16;

And then use the index to be your PK. 

alter table TAB add constraint "PK_<name>" primary key  (col_1, col_2, ... , col_n ) using index MYIDX ;

This took minutes instead of hours and it really saved me! 
 




mercoledì 23 gennaio 2013

Tip: Oracle SQL Developer Data Modeler Create Sequence for an auto incrementing ID

Recently I have started using this tool from Oracle and I must admit it is brilliant for designing Star Schemas and generating DDL code.
For my project I need to define an auto incrementing ID field for several tables of my model. I obviously needed a sequence for each and I was looking for a way to define it in the Data Modeler.
Oracle Data Modeler allows you to mark any column field as auto-incrementing. Select the table in your model and double click on the column. In the example below, I want the primary key field to be auto-incrementing.


Select the option Auto-Incrementing in the Column Property panel.



If you check the DDL you will see the code for the sequence and the trigger that is fired whenever a new line is inserted into the table.

CREATE SEQUENCE CNE_CNEIDE_SEQ
    NOCACHE
    ORDER ;

CREATE OR REPLACE TRIGGER CNE_CNEIDE_TRG
BEFORE INSERT ON T_CANAL_ENTRADA
FOR EACH ROW
WHEN (NEW.CNEIDE IS NULL)
BEGIN
    SELECT CNE_CNEIDE_SEQ.NEXTVAL INTO :NEW.CNEIDE FROM DUAL;
END;
/


If you don't need the trigger, just untick the option in the Auto Increment panel.