Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create indexes with conditions in Oracle 12c?

I want to migrate a PostgreSQL database into Oracle 12c, and for example in the table creation below, I've found some difficults:

  • How to (if possible) to create these unique indexes with where clause?
  • How to properly add this primary key pessoa_id?
  • Why I get this error 'missing right parenthesis'?

Code:

create table nano.pessoa (
    id              GENERATED BY DEFAULT ON NULL AS IDENTITY,
    nome            varchar(99) not null, 
    sobrenome       varchar(99) not null, 
    nascimento_dt   date,
    registro        varchar(32) not null,   
    fisica_sn       bool default true,   -- no caso de pf, true, pf, falso
    matriz_sn       bool default false,  -- no caso de pf, é o genero, masculino = true
    confirmado_sn   bool default false,
    constraint pessoa_id primary key(id)
);  

create unique index pessoa_juridica_cnpj_ix on pessoas.pessoa (registro) where (fisica_sn = false);
create unique index pessoa_fisica_ix on pessoas.pessoa (nome, sobrenome, nascimento_dt) where (fisica_sn = true);
create unique index pessoa_fisica_cpf_ix on pessoas.pessoa (registro) where ((fisica_sn = true) and ((registro <> null) and (registro <> ''))); 
like image 275
NaN Avatar asked Apr 27 '17 16:04

NaN


People also ask

What are the conditions to create an index?

To create an index in your own schema, one of the following conditions must be true: The table or cluster to be indexed must be in your own schema. You must have the INDEX object privilege on the table to be indexed. You must have the CREATE ANY INDEX system privilege.

Which constraints will create an index automatically?

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.


1 Answers

there is no conditional index in Oracle DB, you can convert the logic to be function based indexes.

so the following :

create unique index pessoa_juridica_cnpj_ix on pessoa (registro) where (fisica_sn = false);

becomes in Oracle SQL :

create unique index pessoa_juridica_cnpj_ix on pessoa (case when fisica_sn = false then registro end) ;
like image 59
lsalamon Avatar answered Oct 17 '22 22:10

lsalamon