3

I'd like to run an insert statement only if a certain condition is met. Is there a way to do that in pure sql?

An example of what I'd like to do in pl/pgsql:

CREATE OR REPLACE FUNCTION set_search_lock (
    userid     IN   integer,
)
    RETURNS boolean AS $body$


DECLARE
BEGIN

    PERFORM 'A' FROM LOCK_TABLE WHERE USERID = userid LIMIT 1;

    IF NOT FOUND THEN
        INSERT INTO LOCK_TABLE (USERID) VALUES (userid);
        RETURN true;
    ELSE
        RETURN false;
    END IF;


END;
$body$
LANGUAGE PLPGSQL;
Hartwig
  • 1,353
  • 2
  • 16
  • 26

1 Answers1

5

Assuming you want to insert the value 42, then the following will only insert a row if there isn't one already:

insert into lock_table (userid) 
select 42
where not exists (select 1 from lock_table where userid = 42);