I have a table with two columns, A and B. Each pairing (a, b) should only occur once in the table. When I query this table, I will only be interested in those rows where A has a certain value. Is a two column primary key (A,B) the way to go even though my queries will only search on A?
|
migrated from stackoverflow.com Jun 18 '12 at 3:30
|
If you define the primary key as If you define the primary key as |
|||
|
|
|
The primary key is not there as a mechanism to improve performance (by adding an index) it is there to guarantee data consistency. Design it to do that. If, at the same time, the index that comes with a PK improves performance on some specific query or group of queries, or if by ordering the columns in the PK properly it can be made to do that, great, but performance considerations should not ever drive the selection of the primary key columns! |
|||
|
|
|
No, it will not be the best performing way (for reads in general). Although it will be used when querying only against a, less keys will fit per page in the index as compared to an index only on a and so be less efficient because the keys are longer. This will get worse depending upon the ratio of the size of b to a, i.e. the proportion of the key used for b which is effectively wasted space. However, if you are querying only for a single or very few specific values of a rather than a range, the effect may not be significant, since you wouldn't be going through many pages. I would add the unique index on both to meet data integrity constraints for your problem domain but see if the performance is better for your overall load by adding an index on a alone (note that having to update two indexes will slow performance on writes). |
|||
|
|