postgreSQL sorting with timestamps

时间秒杀一切 提交于 2019-12-11 00:25:04

问题


I have the following SQL statement:

SELECT * FROM schema."table"
  WHERE "TimeStamp"::timestamp >= '2016-03-09 03:00:05'
  ORDER BY "TimeStamp"::date asc
  LIMIT 15

What do I expect it to do? Giving out 15 rows of the table, where the timestamp is the same and bigger than that date, in ascending order. But postgres sends the rows in the wrong order. The first item is on the last position. So has anyone an idea why the result is this strange?


回答1:


Use simply ORDER BY "TimeStamp" (without casting to date).




回答2:


By casting "TimeStamp" to date you throw away the time part of the timestamp, so all values within one day will be considered equal and are returned in random order. It is by accident that the first rows appear in the order you desire.

Don't cast to date in the ORDER BY clause if the time part is relevant for sorting.

Perhaps you are confused because Oracle's DATE type has a time part, which PostgreSQL's doesn't.



来源:https://stackoverflow.com/questions/38457297/postgresql-sorting-with-timestamps

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