0

I have this query. Assuming no index is created yet, how can i optimize this using index so the query runs faster? How do i create the index?

select c.company_name, c.company_id FROM companies AS c 
JOIN users AS u USING(companyid) 
JOIN jobs AS j USING(userid) 
JOIN useraccounts AS ua USING(userid) 
WHERE j.jobid = 10;

Any help would greatly be appreciated.

1 Answer 1

1

You should have indexes on all the columns used in the JOIN clauses. You can create the indexes either with CREATE INDEX or ALTER TABLE commands:

CREATE INDEX u_companyid ON users (companyid);

ALTER TABLE users ADD INDEX (companyid);

Note that primary keys of tables are already indexed, you don't need to add an index explicitly.

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

6 Comments

do you mean i must add index on users.company_id, jobs.user_id and useraccounts.user_id? if yes, am i missing other columns thats needed to be indexed??
@MarkBonnieVestil exactly
@Barmar thanks man. How about indexing companies.company_id. Will it help for faster performance on my query above?
Isn't that the primary key?
Yes, I said that in the last line of my answer. Primary keys already have an index.
|

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.