ATM I am trying to learn how to efficiently use database inidices and would appreciate to get some expert input. I do not have any performance issues currently. I would just like to know, how you would handle your indices with this query:
SELECT B.event,
COALESCE(B.system, C.surname || ' ' || C.forename) AS name,
C.label,
B.timestamp
FROM A
INNER JOIN B ON A.event=B.event
INNER JOIN C ON B.state=C.id
LEFT OUTER JOIN D ON B.hur=D.id
WHERE A.id IN(12,13,14,15,...)
ORDER BY B.event, B.timestamp
A.id
, C.id
and D.id
are already primary keys
UPDATE normally i would put INDEX(A.event) and INDEX(B.event, B.timestamp). Is this correct? And what about B.event, B.state and B.hur ?
The fastest way to speed up the update query is to replace it with a bulk-insert operation. It is a minimally logged operation in simple and Bulk-logged recovery model. This can be done easily by doing a bulk-insert in a new table and then rename the table to original one.
If you are running a query and it's slow, it could benefit from indexes. Indexes are often the most useful when created on columns as part of the Join clause and the Where clause. So, check which columns are used there, check if they have indexes, and create them if they don't.
Rewrite your query as this:
SELECT B.event,
COALESCE(B.system, C.surname || ' ' || C.forename) AS name,
C.label,
B.timestamp
FROM B
INNER JOIN
C
ON C.id = B.state
LEFT OUTER JOIN
D
ON D.id = B.hur
WHERE B.event IN
(
SELECT event
FROM A
WHERE A.id IN (12, 13, 14, 15)
)
ORDER BY
B.event, B.timestamp
, and create a composite index on B (event, timestamp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With