Evan Salter
Evan Salter

Reputation: 1219

INSERT INTO: Reference another field in VALUES statement

I have the following INSERT statement:

 33 INSERT INTO
 34         Exhibitions (
 35                 ex_eName,
 36                 ex_eDescription,
 37                 ex_eDateStart,
 38                 ex_eDateEnd)
 39 VALUES
 40         ('exhibition name',
 41         'exhibition description',
 42         (SELECT
 43                 dateStart
 44         FROM
                   ...
 62         ),
 63         '2017-10-10'); -- this date is a placeholder
 64

I am inserting a record into Exhibitions with 4 fields: Exhibition name, Exhibition description, Start date, End date. I am using some subqueries to find a Start date (I took out the subqueries because it is not relevant to the question).

The end date should be 5 months after the start date. I can't figure out how to reference the start date field when I'm defining the end date field. Here is an example of what I want to do:

 33 INSERT INTO
 34         Exhibitions (
 35                 ex_eName,
 36                 ex_eDescription,
 37                 ex_eDateStart,
 38                 ex_eDateEnd)
 39 VALUES
 40         ('exhibition name',
 41         'exhibition description',
 42         (SELECT
 43                 dateStart
 44         FROM
                   ...
 62         ),
 63         dateStart + interval '5 months');
 64

Is this possible in PostgreSQL?

Upvotes: 1

Views: 1602

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270883

Use insert . . . select:

INSERT INTO Exhibitions (ex_eName, ex_eDescription, ex_eDateStart, ex_eDateEnd)
    SELECT 'exhibition name', 'exhibition description', datestart,
           dateStart + interval '5 months'
    FROM . . .;

Upvotes: 1

Related Questions