postgreSQL sorting with timestamps

2019-08-15 07:58发布

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. SQL Editor with result So has anyone an idea why the result is this strange?

2条回答
forever°为你锁心
2楼-- · 2019-08-15 08:44

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

查看更多
干净又极端
3楼-- · 2019-08-15 08:47

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.

查看更多
登录 后发表回答