I have a mysql table storing members messages with 4 columns :
- message_id (primary key, auto incrementing)
- sender_id (key)
- receiver_id (key)
- message_content
I do lots of SELECTs and I always sort them by message_id DESC, with queries such as :
SELECT message_content
FROM table
WHERE sender_id='3333'
ORDER BY message_id DESC
LIMIT 30
in such queries, the ORDER BY is expensive (it typically has to sort through thousands of rows, which generates some load when multiplied by many requests each second)
Is there a way to avoid having to sort the table each time? Since I always want to retrieve results in the same order, and since the message_id column doesn’t change over time, if each new table row was inserted in first position, the table would always be sorted and i wouldn’t need any “ORDER BY” anymore.
Is that possible ? Or are there other solutions?
Thank you
3333as an integer, not a string (remove quotes)message_idcolumn to thesender_idindex (if you use myisam, because in innodb it is added automatically by so called “clustered index“)