Skip to content
Advertisement

Can you use ORDER BY (column) LIMIT with a secondary column?

I want to find out the Top 10 rented movies in the sakila db. It must be sorted DESC after total_rentals and secondary after film title. My solution looks like this and works so far without the film title:

However, I can’t sort it after film.title due to syntax error(Error 1064).

Can someone help me out?

Advertisement

Answer

Is this what you want?

This guarantees just 10 rows in the resultset, sorted by descending total_rentals, then by film title.

Another way to read your question: give me the 10 best rental scores, and the associated movies – which may yield more than 10 rows if there are ties. In that case, I would recommend window functions (available in MySLA 8.0)

Notes:

  • COUNT(*) is more efficient than COUNT(<something>) and is equivalent here

  • I wouldn’t expect “orphan” rows in rental; if so, INNER JOINs are more appropriate than LEFT JOINs

  • It is probably a good idea to add film_id to the GROUP BY clause, in case there are title homonyms

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement