Quick SQL/Oracle question...

Status
Not open for further replies.

Dandy Andy

Ars Tribunus Militum
2,458
CREATE UNIQUE INDEX blah_id_idx ON blah(blah_id) ;

and

CREATE UNIQUE INDEX blah_name_idx ON blah(blah_name) ;

will do what you want. If the combination of BLAH_ID and BLAH_NAME only must be unique, then a concatenated index will do the job:

CREATE UNIQUE INDEX blah_id_name_idx ON blah(blah_id,blah_name) ;

Just make sure you get the columns the right way round. On versions of Oracle earlier than 9i, the following SQL will NOT use the index BLAH_ID_NAME_IDX, even though the index contains the specified column:

SELECT * FROM blah WHERE blah_name = 'ELLISON' ;

But the following WILL use the index:

SELECT * FROM blah WHERE blah_id = 102 ;

This is because you need to specify all leading columns for the optimiser to use a concatenated index. The other option is to have two concatenated indexes, each with the two columns in the opposite order. The overhead on INSERT will go up though, so be careful!

;)
 
This is because you need to specify all leading columns for the optimiser to use a concatenated index. The other option is to have two concatenated indexes, each with the two columns in the opposite order. The overhead on INSERT will go up though, so be careful!

Actually, that's not a good idea. If you want to enforce uniqueness and support both query types, you would build one composite index (A,B), then one single index on the second attribute (B).

I know it's a bit nitpicky, but then again, so is optimizing Oracle. :)
 
Status
Not open for further replies.