Skip to content

Instantly share code, notes, and snippets.

@gdetrez
Last active August 29, 2015 13:56
Show Gist options
  • Save gdetrez/9072761 to your computer and use it in GitHub Desktop.
Save gdetrez/9072761 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE TRIGGER BidHighEnough
BEFORE INSERT ON Bids
REFERENCING NEW AS new
FOR EACH ROW
DECLARE numHigherBids INT;
BEGIN
SELECT COUNT(amount) INTO numHigherBids
FROM Bids
WHERE item = :new.item AND amount > :new.amount;
IF ( numHigherBids > 0 ) THEN
RAISE_APPLICATION_ERROR(-20000, 'bid not high enough');
END IF;
END;
CREATE OR REPLACE FUNCTION bid_high_enough() RETURNS TRIGGER AS $_$
BEGIN
IF EXISTS (SELECT * FROM bids WHERE item = NEW.item AND amount > NEW.amount) THEN
RAISE EXCEPTION 'Bid not high enough';
END IF;
RETURN NEW;
END $_$ LANGUAGE 'plpgsql';
DROP TRIGGER IF EXISTS BidHighEnough ON bids;
CREATE TRIGGER BidHighEnough BEFORE INSERT ON Bids
FOR EACH ROW
EXECUTE PROCEDURE bid_high_enough();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment