2

Good day,

I'm having trouble with my query, as I can't seem to understand why I keep getting the error "syntax error at or near "AS" here's my query:

    CREATE TRIGGER  updateAvailableQuantity
    AFTER INSERT ON sale_item FOR EACH ROW 
    AS $$
    BEGIN
        IF NEW.quantity > 0 THEN
        UPDATE products
        SET products.quantity_instock = products.quantity_instock - NEW.quantity WHERE barcode =  NEW.barcode;
        END IF;
    END;
    $$ LANGUAGE plpgsql;

the error that I keep getting is,

    ERROR:  syntax error at or near "AS"
    LINE 4: AS $$
            ^
    SQL state: 42601
    Character: 100

2 Answers 2

4

You can not write trigger in PostgreSQL in this way. Here its a 2 step process.

  1. First create a Trigger function:
CREATE OR REPLACE FUNCTION updateAvailableQuantity()
RETURNS TRIGGER
AS
$$
BEGIN
    IF NEW.quantity > 0 THEN
    UPDATE products
    SET quantity_instock = quantity_instock - NEW.quantity WHERE products.barcode =  NEW.barcode;
    END IF;

RETURN NULL;
END;
$$ LANGUAGE plpgsql;
  1. Then write the trigger on your table to call the function like below:
CREATE TRIGGER  trg_updateAvailableQuantity
AFTER INSERT ON sale_item 
FOR EACH ROW 
EXECUTE PROCEDURE updateAvailableQuantity();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Finally, it worked. I was in complete enigma as why this wasn't working and in mysql workbench, it works completely fine.
-1

You have an error in your syntax. See the documentation page on create trigger.

FOR EACH ROW can not go before REFERENCING AS statement.

The documentation also has a plenty examples.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.