简体   繁体   中英

How do I find the earliest date in PostgreSQL?

I am working with a Postgres table that has a field named first_contact_date where it is of type date. I am using the the mm/dd/yyyy representation of a date. My query works correctly as written but it orders literally by month.

SELECT first_contact_date 
FROM schema.table 
ORDER BY first_contact_date

For example "10/3/2016" would go after "1/2/2017", even though in a date sense, it should be "1/2/2017" that goes after "10/3/2016".

I have looked at

  1. How to find the earliest and latest date from a database , but its too vague and I am using an order by already.
  2. SQL ordering by earliest date in group , but I am using a different format.
  3. How do I return the record with the earliest date? , ditto with number 2

and

  1. PostgreSQL query where date oldest , but this limits it to one year

How to I structure the query so that the earliest date from a calendar perspective is returned?

You can extract interval starting from beginning of year and order by it:

SELECT first_contact_date-date_trunc('year',first_contact_date), first_contact_date
FROM schema.table 
ORDER BY 1;

Edit: Long years might not work properly as duration starting from begining of year might differ after February.

This is a bit dirty, but will work correctly also for long years:

    SELECT to_char(first_contact_date,'MM')::int*100+to_char(first_contact_date,'DD')::int datenum
FROM schema.table 
ORDER BY 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM