1

I'm trying to optimize queries modelled on the following example:

UPDATE posts
SET title = "Example", lock_version = 1
WHERE (
    posts.id = 123
    AND
    posts.lock_version = 0
)

I have a unique index on posts.id, which ensures that positive hits on WHERE posts.id = 123 will never return more than one result.

Do I also need an index on posts.lock_version?

I imagine I would need it if the first part of the WHERE returned more than one result, because the index would make it faster to narrow down the filter.

What about the situation I described, though?

1
  • If posts.id is a primary key (or otherwise unique: a candidate key) then alll other columns are functionally dependant on it , and an extra index would not be needed, given that you always use the PK to address a row, Commented Dec 1, 2014 at 18:20

1 Answer 1

3

No. If posts.id is unique, you don't need more than the simple index on that column.

It won't get any faster - on the contrary: since you update the row, you would add maintenance cost to update the additional index as well.

Aside: you don't need the parentheses in your WHERE clause:

...
WHERE id = 123
AND   lock_version = 0

And if you double-quote "Example" it refers to a column of that name. You probably want the value: 'Example'. Single quotes for a string literal.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Yes, you're also right about the format.

Your Answer

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.