PHP5000 Posted 19 hours ago Share Posted 19 hours ago (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 18 hours ago 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 17 hours ago Share Posted 17 hours ago 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 11 hours ago Author Share Posted 11 hours ago (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 11 hours ago 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 11 hours ago Share Posted 11 hours ago 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 10 hours ago Author Share Posted 10 hours ago 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 4 hours ago Share Posted 4 hours ago 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.