PHP5000 Posted November 26 Share Posted November 26 (edited) Hi Any idea what is SQL command to select the oldest 20 records in a Mysql table? I know it can be done with reading the number of records and recording the oldest id and newest id and setting a range, but I am trying to find a more efficient and quicker way to do this. (In a single SQL command). Thanks in advance Edited November 26 by PHP5000 Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/ Share on other sites More sharing options...
Barand Posted November 26 Share Posted November 26 select <whatever> from <tablename> order by date_created limit 20 Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/#findComment-1642200 Share on other sites More sharing options...
PHP5000 Posted November 27 Author Share Posted November 27 (edited) Brand this would only work if I had a column saving the dates (date_created), which I do not. Also supposing I wanted to delete the records. Any idea how to adopt this notion to DELETE, specially without date ? Thanks in advance Edited November 27 by PHP5000 Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/#findComment-1642332 Share on other sites More sharing options...
mac_gyver Posted November 27 Share Posted November 27 you would ORDER BY the id (autoincrement primary index) column instead. a DELETE query has the same ORDER BY and LIMIT terms as a SELECT query. Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/#findComment-1642347 Share on other sites More sharing options...
PHP5000 Posted November 27 Author Share Posted November 27 Many thanks to both of you. It worked like a charm. Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/#findComment-1642402 Share on other sites More sharing options...
Barand Posted November 27 Share Posted November 27 7 hours ago, mac_gyver said: you would ORDER BY the id (autoincrement primary index) column instead. But only if you can guarantee that the oldest records are always added first. If relative age is important why would you not store the date added? Having a date also has the advantage that you can have the option to DELETE FROM tablename WHERE datecol < CURDATE() - INTERVAL ? DAY so you can delete all those over N days old Quote Link to comment https://forums.phpfreaks.com/topic/325711-selecting-the-oldest-20-number-of-records/#findComment-1642654 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.