Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql - select something where date = "01/01/11"

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' 

What is the right syntax to do that?

Thanks!

like image 881
Abramodj Avatar asked May 03 '11 21:05

Abramodj


People also ask

How do I select data in PostgreSQL?

If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names. The select list may also contain expressions or literal values. Second, specify the name of the table from which you want to query data after the FROM keyword.

How do I get the latest date record in PostgreSQL?

select product_id, invoice_id, amount from mytable inner join (select max(date) as last_date, product_id, invoice_id from mytable group by product_id) sub on mytable. date = sub. last_date and mytable.

What is now () in PostgreSQL?

The PostgreSQL now function returns the current date and time with the time zone.


2 Answers

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT * FROM table WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD 

Or the standard version:

SELECT * FROM table WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD 

The extract function doesn't understand "date" and it returns a number.

like image 196
mu is too short Avatar answered Sep 19 '22 11:09

mu is too short


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'; 
like image 31
Hugh Avatar answered Sep 20 '22 11:09

Hugh