1

I can't work out how to pass a variable into the postgresql extract function like:

select 'day' as i;
extract(i from a_date)

that gives me

ERROR: timestamp with time zone units "i" not recognized

If I can pass in a string, extract('day' from a_date), why not a variable ?

3
  • 1
    Could you show us the entire script? You have to fetch the result from the SELECT into the next query where you need this result. Or is this about pl/pgsql? Commented Feb 23, 2011 at 7:07
  • 1
    If you're writing a function, then the assignment operation is either SELECT INTO i 'day'; or i := 'day'; Your example does not provide enough context to properly answer the question. Commented Feb 23, 2011 at 9:25
  • how about using an IN parameter: select extract($1 from a_date) - that yields a syntax error Commented Feb 23, 2011 at 23:42

1 Answer 1

5

ANSI SQL doesn't support parameters there. Use a date_part function instead.

http://www.postgresql.org/docs/9.0/interactive/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

postgres=# select extract(day from current_timestamp);
 date_part 
-----------
        23
(1 row)

postgres=# select date_part('day', current_timestamp);
 date_part 
-----------
        23
(1 row)
Sign up to request clarification or add additional context in comments.

1 Comment

ok, but how about passing in a variable ? like select date_part(my_variable, current_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.