Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY id or date_created to show latest results?

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:

  • date_created INT (never changes value)
  • id (INT AUTO_INCREMENT of course!)

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.

like image 210
Wesley Murch Avatar asked Apr 06 '11 18:04

Wesley Murch


4 Answers

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.

like image 151
drewrobb Avatar answered Oct 07 '22 19:10

drewrobb


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.

like image 32
niczak Avatar answered Oct 07 '22 18:10

niczak


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.

like image 3
Dane Avatar answered Oct 07 '22 20:10

Dane


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.

like image 2
vbence Avatar answered Oct 07 '22 18:10

vbence