I have a table (several actually) that I want to get results from with the most recent entries first. Here are my ORDER BY
clause options:
Both columns should equally represent the order in which the records were inserted. I naturally would use the date_created
field like any sane person would, but I'm still curious about this.
I know this is probably splitting hairs, but is there any reason or edge case why I should NOT use the id
column?
EDIT: I'm thinking that this question is vague as to which value we want to truly represent the insert order. Thank you for all your answers everybody, I am going to accept the best one and move on because I think I have made this difficult by assuming that ids will always be in order (see @Wrikken's comment). My gut instinct is that id should never be considered by the developer, which is what most of the answers here are pointing to.
It isn't a good idea to depend on the ID column for time ordering, because that isn't its purpose. Basically, the ID is just a unique key for that row, nothing more. Using ID might never cause problems, but there is no reason to add complexity of assuming that ordering by ID will always hold. For instance, you might in the future want to delete entries and then manually insert new entries, or import entries from some other source that are timestamped in the past. If you didn't have a date_created column, then ID would be your only option, but since you have the column, use it, as it is your best choice.
Assuming date_created never gets touched (you have stated that it doesn't) I think sorting by the ID column would be better in terms of performance. Presumably the ID column is your pkey and thus already indexed. No reason not to use it for sorting. I know the case has been made that you should always use a date for ordering but honestly in this case I would use the ID.
One good reason, as a rule - because you (or someone who inherits your app) may retroactively insert a record with a older timestamp (that is, explicitly set the timestamp to something in the past rather than the current). You can't always rely on the ID sorting matching the timestamp sorting.
In general you should not rely on IDs, if you already have a field devoted to creation time. Maybe in case of collision (records created in exactly the same moment) you can use ID as a secondary order clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With