0

I have a PostgreSQL trigger function like so:

CREATE FUNCTION playlists_tld_update_trigger() RETURNS TRIGGER AS
    $$
    BEGIN
      IF EXISTS (SELECT 1 FROM "subjects" WHERE "subjects"."id" = new.subject_id) THEN
        new.tld = (SELECT "subjects"."tld" FROM "subjects" WHERE "subjects"."id" = new.subject_id LIMIT 1);
      END IF;
      RETURN new;
    END
    $$
    LANGUAGE plpgsql;

The trigger function will set the playlist's "tld" column to match the subject's "tld" column, but only if there exists a subject referenced by the subject_id foreign key. How do I use a subquery to combine the 2 queries into 1, or to avoid redundancy?

1 Answer 1

2
CREATE FUNCTION playlists_tld_update_trigger()
RETURNS TRIGGER
AS $$
DECLARE
    my_tld <data_type_of_tld>;
BEGIN
    SELECT subjects.tld
      INTO my_tld
      FROM subjects
     WHERE subjects.id = new.subject_id
     LIMIT 1
    ;
    IF FOUND
    THEN
        new.tld = my_tld;
        RETURN NEW;
    ELSE
        -- do something else
        RETURN OLD;
    END IF;
END
$$ LANGUAGE plpgsql;
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.