Postgresql - select something where date = “01/01/11”

前端 未结 2 967
孤独总比滥情好
孤独总比滥情好 2021-01-31 07:13

I have a datetime field in my Postgresql, named \"dt\". I\'d like to do something like

SELECT * FROM myTable WHERE extract (date from dt) = \'01/01/11\'
         


        
2条回答
  •  误落风尘
    2021-01-31 08:01

    With PostgreSQL there are a number of date/time functions available, see here.

    In your example, you could use:

    SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
    

    If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

    CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
    

    One advantage of this is there is some more flexibility with timezones if required, for example:

    CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
    SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
    

提交回复
热议问题