0

I need to insert some rows to tables in PostgreSQL. But before inserting the row into table, I should check whether the record is existing or not by using update statement. If update statement returns 0 rows, then I can insert, otherwise I can skip that insertion. I should write SQL statements for this in .sql file in PostgreSQL.

How to achieve this?

In Oracle we have below format:

declare
  i number;
begin
  update employees set status = 'fired' where name like '%Bloggs';
  i := sql%rowcount;
IF i ==0 THEN
insert statement here
end

How can I achieve this in Postgres?

3
  • Can you please suggest me whether it is possible or not. Commented Aug 5, 2014 at 5:22
  • You want to match each column? Commented Aug 5, 2014 at 5:38
  • Got answer using GET DIAGNOSTICS l = ROW_COUNT; in postgre sql Commented Aug 5, 2014 at 6:49

1 Answer 1

1

If concurrency is not a problem for you, and you want to do it in a plpgsql function, rather use the special variable FOUND:

DO
$do$
BEGIN

UPDATE employees SET status = 'fired' WHERE ... ;

IF NOT FOUND THEN
   -- insert statement here
END IF;

END
$do$

Or use a data-modifying CTE:

If concurrency is relevant, read up on proper UPSERT solutions.

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

Comments

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.