HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Is a two column primary key the most performant way to go if (a,b) should be unique but I will only be querying against a?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
uniquetheprimarycolumnbutwayqueryingagainsttwowill

Problem

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?

Solution

If you define the primary key as (a,b), then the index will be used when handling queries using a OR a AND b, but not b alone.

If you define the primary key as (b,a), then the index would be used when handling b, b AND a, but not a alone.

Context

StackExchange Database Administrators Q#19413, answer score: 10

Revisions (0)

No revisions yet.