0

I want to insert a row into postgresql if not exist into table. My table structure is as below.

Table Name: test

id serial NOT NULL

unitid integer

eventid integer

date_time timestamp without time zone

I tried following query but gives me error near Select.

INSERT INTO test VALUES (905, 10, '2015-09-23 13:34:26')
SELECT 905, 10, '2015-09-23 13:34:26'
WHERE NOT EXISTS(
SELECT 1
FROM test
WHERE unitid = 905 AND eventid = 10 AND date_time = '2015-09-23 13:34:26'
);

Please any one give me good suggestion about it. I want faster way to do this.

1 Answer 1

1

You are specifying values and then you are including a selection. You need to write your insert into without values(...) and use the select you have there instead. Simple example

insert into items_ver
select * from items where item_id=2;

taken from here. Try your selection first. Is

SELECT 905, 10, '2015-09-23 13:34:26'
WHERE NOT EXISTS(
SELECT 1
FROM test
WHERE unitid = 905 AND eventid = 10 AND date_time = '2015-09-23 13:34:26'
);

If so, then you should have an insertion like this:

INSERT INTO test
SELECT 905, 10, '2015-09-23 13:34:26'
WHERE NOT EXISTS(
SELECT 1
FROM test
WHERE unitid = 905 AND eventid = 10 AND date_time = '2015-09-23 13:34:26'
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This is the best answer. Performance wise I have aroung 100,000 data and perform operation in around 22 ms. Thank you so much.

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.