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)
-
1You 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.Bill Karwin– Bill Karwin2018年06月12日 00:18:10 +00:00Commented Jun 12, 2018 at 0:18
-
Possible duplicate of Two single-column indexes vs one two-column index in MySQL?revo– revo2018年06月12日 00:18:30 +00:00Commented Jun 12, 2018 at 0:18
-
1You seem to be confusing primary keys with indexes.Barmar– Barmar2018年06月12日 00:37:56 +00:00Commented Jun 12, 2018 at 0:37
2 Answers 2
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 have
PRIMARY 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.
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)