1

We have a table that is currently using a composite (i.e. multi-column) index.

Let's say

PRIMARY KEY(A, B)

Of course we can rapidly search based on A alone (Leftmost Index Prefix) and if we want to efficiently search based on B alone, we need to create a separate index for B.

My question is that if I am doing:

PRIMARY KEY (B)

is there any value in retaining

PRIMARY KEY (A,B)

In other words will there be any advantage retaining

PRIMARY KEY (A,B)

if I have

PRIMARY KEY (A)

and

PRIMARY KEY (B)
asked Jun 12, 2018 at 0:10
3
  • 1
    You can't have more than one primary key constraint in a table. The purpose of the primary key is to define the columns you can use to select any row individually. Commented Jun 12, 2018 at 0:18
  • Possible duplicate of Two single-column indexes vs one two-column index in MySQL? Commented Jun 12, 2018 at 0:18
  • 1
    You seem to be confusing primary keys with indexes. Commented Jun 12, 2018 at 0:37

2 Answers 2

1

You are missing a key point about PRIMARY KEY -- it is by definition (at least in MySQL), UNIQUE. And do not have more columns than are needed to make the PK unique.

If B, aloneis unique, then havePRIMARY KEY(B)` without any other columns in the PK definition.

If A is also unique, then do

PRIMARY KEY(B),
UNIQUE(A)

or swap them.

For a longer discussion of creating indexes, see my cookbook.

If it takes both columns to be "unique", then you may need

PRIMARY KEY(A, B),
INDEX(B)

or

PRIMARY KEY(B, A),
INDEX(A)

Until you have the SELECTs, it is hard to know what indexes to create.

answered Jun 12, 2018 at 3:14
0

You can't have multiple primary keys, so I'm going to assume you're really asking about having an ordinary index.

If you have an index on (A, B), it will be used for queries that use both columns, like:

WHERE A = 1 AND B = 2

as well as queries that just use A:

WHERE A = 3

But if you have a query that just uses B, e.g.

WHERE B = 4

it will not be able to use the index at all. If you need to optimize these queries, you should also have an index on B. So you might have:

UNIQUE KEY (A, B)
INDEX (B)
answered Jun 12, 2018 at 0:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.