Here's a way to create a table with clustered index on a composite primary key. A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore, the table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. Clustered indexes are more preferable than nonclustered if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY. Generally, we have GROUP BY or ORDER BY on primary keys. But the RDBMS system creates a non-clustered index as soon as you define a PK. To have our own clustered index on PK columns, we have to go this way and fool the RDBMS. It works on DB2 UDB v7.1.
Here's the procedure:
- Create a table with no primary key defined.
- Create clustered index on the primary key columns.
- Alter the table to define the primary key.
create table CDSWEB.PRASHANT (officeid integer not null, empid integer not null, age integer ,sex varchar(5), name varchar(20));Index creation:
create index CDSWEB.PRAN001 on CDSWEB.PRASHANT(officeid,empid) CLUSTER;Primary key defined:
alter table CDSWEB.PRASHANT add primary key (officeid,empid);
For More Information
- Feedback: E-mail the editor with your thoughts about this tip.
- More tips: Hundreds of free DB2 tips and scripts.
- Tip contest: Have a DB2 tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize -- submit your tip today!
- Ask the Experts: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
- Forums: Ask your technical DB2 questions--or help out your peers by answering them--in our active forums.
- Best Web Links: DB2 tips, tutorials, and scripts from around the Web.