Note that there are some explanatory texts on larger screens.

plurals
  1. POIn SQL how can I use an index to speed up this database query?
    primarykey
    data
    text
    <p>I have two tables:</p> <p><img src="https://i.stack.imgur.com/Rtnxx.png" alt="enter image description here"></p> <pre><code>CREATE TABLE `album` ( `album_id` int(10) unsigned NOT NULL, `artist_id` int(10) unsigned NOT NULL, `album_type_id` int(10) unsigned NOT NULL, `name` varchar(255) NOT NULL, `first_released` year(4) NOT NULL, `country_id` smallint(5) unsigned DEFAULT NULL, PRIMARY KEY (`album_id`), KEY `artist_id` (`artist_id`), KEY `name` (`name`) ) ENGINE=InnoDB CREATE TABLE `artist` ( `artist_id` int(10) unsigned NOT NULL, `type` enum('Band','Person','Unknown','Combination') NOT NULL, `name` varchar(255) NOT NULL, `gender` enum('Male','Female') DEFAULT NULL, `founded` year(4) DEFAULT NULL, `country_id` smallint(5) unsigned DEFAULT NULL, PRIMARY KEY (`artist_id`), KEY `name` (`name`) ) ENGINE=InnoDB; </code></pre> <p>My first query:<br></p> <pre><code>select ar.name, count(*) from artist ar join album al on ar.artist_id=al.artist_id group by ar.artist_id limit 10; </code></pre> <p>which produces a result set in 0.00 seconds.</p> <p>I would like to order the results, so I add "order by 2 desc":</p> <pre><code>select ar.name, count(*) from artist ar join album al on ar.artist_id=al.artist_id group by ar.artist_id order by 2 desc limit 10; </code></pre> <p>but now the result set takes over 5 seconds, which is too slow.</p> <p>Execution plan: <img src="https://i.stack.imgur.com/xP6wi.png" alt="enter image description here"></p> <p>How can I add an index to speed up my new query?</p> <p>Sample data: <a href="http://bit.ly/1k5ROrT" rel="nofollow noreferrer">http://bit.ly/1k5ROrT</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload