4

If my table looks like this

CREATE TABLE public.temperatures (
  temperature_io_id        integer NOT NULL,
  temperature_station_id   integer NOT NULL,
  temperature_value        double precision NOT NULL,
  temperature_current_kw  double precision NOT NULL,
  temperature_value_added  integer DEFAULT 1,
  temperature_kw_year_1   double precision DEFAULT 0,
  /* Keys */
  CONSTRAINT temperatures_pkey
    PRIMARY KEY (temperature_io_id, temperature_station_id, temperature_value)
) WITH (
    OIDS = FALSE
  );

I'm trying to add values to the table when there is a unique combination of io_id, station_id and temperature. If this combination already exists, i want to update the kw value and add 1 to the value_added field. This will be used to keep a running average of the kw at the temperature.

INSERT INTO temperatures
(temperature_io_id, temperature_station_id, temperature_value, temperature_curr_kw)
VALUES
(20,30,40,10)
ON CONFLICT
(temperature_io_id, temperature_station_id, temperature_value)
DO UPDATE SET    
temperature_current_kwh = ((temperature_current_kw * temperature_value_added) + EXCLUDED.temperature_current_kw) / (temperature_value_added + 1),
                        temperature_value_added = temperature_value_added + 1;

How can i access the values from the row when im doing the update? I get an ambiguous error when i try to access temperature_current_kw?

1
  • I think I figured out a solution. If i put the table name infront of the columns so like temperatures.temperature_current_kw that would access the data point that had the insert conflict? Commented Jan 28, 2016 at 21:06

1 Answer 1

6

Use a table alias:

INSERT INTO temperatures as t
    (temperature_io_id, temperature_station_id, temperature_value, temperature_current_kw)
VALUES
    (20,30,40,10)
ON CONFLICT
    (temperature_io_id, temperature_station_id, temperature_value)
DO UPDATE SET    
    temperature_current_kw = ((t.temperature_current_kw * t.temperature_value_added) + EXCLUDED.temperature_current_kw) / (t.temperature_value_added + 1),
    temperature_value_added = t.temperature_value_added + 1;

As stated in the documentation:

alias

A substitute name for table_name. When an alias is provided, it completely hides the actual name of the table. This is particularly useful when ON CONFLICT DO UPDATE targets a table named excluded, since that's also the name of the special table representing rows proposed for insertion.

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

1 Comment

Thanks this is exactly what i needed.

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.