'Syntax error at end of input with IF ... ELSE statement

I'm running this code:

CREATE OR REPLACE FUNCTION trg_orders_check()
  RETURNS trigger
  LANGUAGE plpgsql AS
$func$
BEGIN
  IF NEW.type = 'prescription' AND NEW.prescription_id IS NULL THEN
    RAISE EXCEPTION 'Must include prescription_id';
  ELSE IF NEW.TYPE = 'item' AND NEW.item_id IS NULL THEN
    RAISE EXCEPTION 'Must include item_id';
  ELSE
    RAISE EXCEPTION 'Type must be either prescription or item';
  END IF;
END
$func$;

I get the error:

syntax error at end of input

What's wrong with it?



Solution 1:[1]

The syntax error has been pointed out in the comments. It's ELSIF or ELSEIF.

More importantly, your logic is broken. You would reach the exception 'Type must be either prescription or item' when everything is ok.

You most probably want something like this:

CREATE OR REPLACE FUNCTION trg_orders_check()
  RETURNS trigger
  LANGUAGE plpgsql AS
$func$
BEGIN
   CASE NEW.type
   WHEN 'prescription' THEN
      IF NEW.prescription_id IS NULL THEN
         RAISE EXCEPTION 'Must include prescription_id';
      END IF;
   WHEN 'item' THEN
      IF NEW.item_id IS NULL THEN
         RAISE EXCEPTION 'Must include item_id';
      END IF;
   ELSE
      RAISE EXCEPTION 'Type must be either prescription or item';
   END CASE;
END
$func$;

Using a "switched" CASE. See:

You could also use separate IF statements, but this is probably the best way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Erwin Brandstetter