I have a SQL statement like this:
insert into table1 (col1, col2, col3, col4)
select
value1,
value2,
now(),
now()
from
othertable inner join anotherothertable on somecolumn = someothercolumn;
The select
component of this query will return many hundreds of thousands of rows.
How will the call to now()
behave?
- Will it return the same value for all rows inserts?
- Will it return the same value in the same insert, given that it appears to be called twice per single row insertion?
I want to perform this insert such that now()
is called once, and that value is fixed and used when inserting all the rows and data. I am not sure if this query will behave this way or not.
Since there is no way to do something like current_timestamp = now()
in SQL and use current_timestamp
as an argument in place of the two calls to now()
, I am not sure how to do this.
4
Answers
You can Store the value in new variable and save it like this :
Declaring and using a variable is best option IMHO.
DBFiddle demo
This is thoroughly documented at Date/Time Functions and Operators but, essentially, your code is fine as is if your intention is to have the same time in every row. It’ll return the same value for each individual statement, or even the whole transaction.
You can do a quick test:
The calls to function ‘now’ in your statement return the same time for all rows in
your statement. The time returned is the time the current transaction was started,
which is at the time of the current statement or an earlier statement in the
transaction.
The documentation for that is in the Postgres manual, 9.9.5. Current Date/Time.
Here is a summary:
So, you don’t need to put the time into a ‘variable’. If for some reason, you still
wanted to do that, you can isolate the time into a ‘variable’ with the help of a
common table expression (WITH query), without leaving SQL: