ORDER BY id or date_created to show latest results?

半世苍凉 提交于 2019-12-10 17:36:38

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


Say you run yourself out of positive integers on the id and you change your auto increment to use negative ints. Your order by id would not return the most recent records first.

Hey, you asked for an edge case! ;-)



来源:https://stackoverflow.com/questions/5570958/order-by-id-or-date-created-to-show-latest-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!