I want to make a query "If a record within that second and this sensor_id exists, update it with provided new value, else create a record with that value, sensor_id and time".
I managed to create this query:
DO
$do$
BEGIN
IF EXISTS (
SELECT
1
FROM
public.measurement_pm2_5
WHERE
measurement_time >= TO_TIMESTAMP('06.07.2016 23:28:43', 'DD.MM.YYYY HH24:MI:SS')
AND measurement_time < TO_TIMESTAMP('06.07.2016 23:28:44', 'DD.MM.YYYY HH24:MI:SS')
AND sensor_id = 2
) THEN UPDATE
public.measurement_pm2_5
SET
measurement_value = 27
WHERE
measurement_time >= TO_TIMESTAMP('06.07.2016 23:28:43', 'DD.MM.YYYY HH24:MI:SS')
AND measurement_time < TO_TIMESTAMP('06.07.2016 23:28:44', 'DD.MM.YYYY HH24:MI:SS')
AND sensor_id = 2;
ELSE INSERT
INTO
public.measurement_pm2_5
( sensor_id, measurement_time, measurement_value )
VALUES
( 2, TO_TIMESTAMP('06.07.2016 23:28:43', 'DD.MM.YYYY HH24:MI:SS'), 27 );
END IF;
END;
$do$
LANGUAGE plpgsql;
But it doesn't work as expected.
Query OK, 0 rows affected (execution time: 62 ms; total time: 62 ms)
Although this query:
SELECT
1
FROM
public.measurement_pm2_5
WHERE
measurement_time >= TO_TIMESTAMP('06.07.2016 23:28:43', 'DD.MM.YYYY HH24:MI:SS')
AND measurement_time < TO_TIMESTAMP('06.07.2016 23:28:44', 'DD.MM.YYYY HH24:MI:SS')
AND sensor_id = 2
returns one record, the UPDATE part of the first query doesn't look to be executed.
I'm using PostgreSQL 9.5.
What am I doing wrong?
Edit:
measurement_pm2_5 table:
CREATE TABLE public.measurement_pm2_5 (
sensor_id SERIAL,
measurement_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
measurement_value NUMERIC(6,2) NOT NULL,
CONSTRAINT measurement_pm2_5_sensor_id_fkey FOREIGN KEY (sensor_id)
REFERENCES public.sensor(id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE
)
WITH (oids = false);
CREATE TABLE measurement_pm2_5 ( measurement_time timestamp NOT NULL, sensor_id integer NOT NULL DEFAULT 1, measurement_value integer NOT NULL DEFAULT 1 ) WITHOUT OIDS;and it works as expected.dostatement does not return any useful information itself (except when error occurred). Just change yourupdatestatement toUPDATE public.measurement_pm2_5 SET measurement_value = measurement_value + 0.01 ...for example to ensure that all Ok (or not).