0

If I have a query like this

select * from student 
inner join courses on courses.id = student.course_id
where student.gpa >= 3.0
order by student.gpa
limit 50;

How would Mysql execute this query to optimize the cost?

5
  • Run an explain and mysql will tell you. Commented Feb 9, 2021 at 8:35
  • What would the answer that would satisfy you look like? Commented Feb 9, 2021 at 8:35
  • You can use EXPLAIN to see the estimated execution plan, and EXPLAIN ANALYZE to see the actual execution plan. Commented Feb 9, 2021 at 8:36
  • In what flow query would be executed would join be first or where clause would run first? Commented Feb 9, 2021 at 13:24
  • @P.Salmon - EXPLAIN will tell you what it is doing, but not what could be changed to improve it. Commented Feb 26, 2021 at 16:49

1 Answer 1

0

The following index might help:

CREATE INDEX idx ON student (gpa, course_id);

This index would cover the WHERE clause, allowing MySQL to discard any records with a GPA less than 3.0. In addition, it covers the join.

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

2 Comments

why would student table be smaller than courses table. If this is a university database then definitely student will be greater. But thanks for the tip on creating index on where clause column and foreign key.
Furthermore, that index will cover the ORDER BY, thereby letting it get to the LIMIT -- hence it will touch only 50 rows (and not do a sort). Table size and FK are not relevant here. More discussion: mysql.rjweb.org/doc.php/index_cookbook_mysql

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.