1

Have a table "user_order" with columns "user_id", "code" (character varying) and created_date_key (integer). I am trying to write a query which displays all records for code 26 and date greater that '12-5-2013 23:59:59'.

Select *
from user_order
where code like 26 ::text
and to_date(created_date_key ::text, 'YYYY-MM-DD') > to_date ('12-5-2013 23:59:59' ::text, 'YYYY-MM-DD')

ERROR: date format not recognized.

2
  • 2
    Why are you storing a timestamp as an integer? to_date() converts a string (varchar, text) to a date. You cannot pass it an integer. Think about it: how could an integer even when casted to a string possibly have the format 'YYYY-MM-DD' Commented May 23, 2014 at 19:17
  • Assuming your integer is a Unix timestamp or similar (seconds since epoch), you should find what you need here: stackoverflow.com/questions/18747317/… and here: stackoverflow.com/questions/12328817/… Commented May 23, 2014 at 20:32

3 Answers 3

1

created_date_key should be timestamp and not integer.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't change the table structure. That's the way it was build. Just help me with the select statement.
Try to remove the dashes then: Instead of YYYY-MM-DD use that format: YYYYMMDD
1
select *
  from user_order
 where code like 26 ::text
   and to_date(created_date_key ::text, 'YYYY-MM-DD') > '12-5-2013 23:59:59'

3 Comments

Please give some explanation about your answer rather than just the SQL.
to_date(created_date_key ::text, 'YYYY-MM-DD') is not going to work and is exactly what Rohit already tried.
Convert the integer date to date (1st to string and then to date) as you cannot convert a number directly to date and then check if the date converted is greater than '12-5-2013 23:59:59'
0

String values need to be included within single quotes. You do not need to specify text to convert the data type. to_timestamp function is used to convert the text data to timestamp value. The following query would select the required data:

Select *
from user_order
where code = '26'
and created_date_key > to_timestamp ('12-5-2013 23:59:59', 'MM-DD-YYYY HH24:MI:SS');

References:

  1. SELECT on PostgreSQL Manual. There are a lot of examples on this page.
  2. Data Type Formatting Functions on PostgreSQL Manual

1 Comment

created_date_key is a integer. You are trying to compare integer with timestamp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.